首页 > 解决方案 > 我不明白 __add__ 函数在这里是如何工作的?

问题描述

当为 'add_length' 设置 if 条件时,isinstance 有第二个参数 'length' 但在 'add_inches' 的情况下,第二个参数是 int(integer) 。我无法理解这部分。为什么它们不能都是int(整数)。帮助表示赞赏!


    class Length:
        def __init__(self, feet, inches):
            self.feet = feet
            self.inches = inches
    
        def __str__(self):
            return f'{self.feet} {self.inches}'

        def __add__(self, other):
            if isinstance(other, Length):
                return self.add_length(other)
            if isinstance(other, int):
                return self.add_inches(other)
            else:
                return NotImplemented
    
        def __radd__(self, other):
            return self.__add__(other)
    
    
        def add_length(self, L):
            f = self.feet + L.feet
            i = self.inches + L.inches
            if i >= 12:
                i = i - 12
            f += 1
            return Length(f, i)
    
        def add_inches(self, inches):
            f = self.feet + inches // 12
            i = self.inches + inches % 12
            if i >= 12:
                i = i - 12
            f += 1
            return Length(f, i)
    
    
    length1 = Length(2, 10)
    length2 = Length(3, 5)
    
    print(length1 + length2)
    print(length1 + 2`
    print(length1 + 20)
    print(20 + length1)

标签: pythonpython-3.x

解决方案


第一个条件是检查两个长度对象相加时的场景:

length1 = Length(2, 10)
length2 = Length(3, 5)
    
print(length1 + length2)

第二个条件是检查将整数添加到长度时的场景。

print(length1 + 2)
print(length1 + 20)

条件调用两种不同的方法add_lengthadd_inches因为需要访问数据。也就是说,add_length它通过对象 (L) 的属性访问。因为add_inches它是从整数(英寸)访问的。


推荐阅读