python - 我不明白 __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)
解决方案
第一个条件是检查两个长度对象相加时的场景:
length1 = Length(2, 10)
length2 = Length(3, 5)
print(length1 + length2)
第二个条件是检查将整数添加到长度时的场景。
print(length1 + 2)
print(length1 + 20)
条件调用两种不同的方法add_length
,add_inches
因为需要访问数据。也就是说,add_length
它通过对象 (L) 的属性访问。因为add_inches
它是从整数(英寸)访问的。
推荐阅读
- excel - 如何将 vba sub 转换为函数?
- string - 在计算移动平均线时无法将字符串转换为浮点数
- http - http.Request.Clone() 不是深度克隆?
- javascript - 接口的按位“或”运算符是什么意思
- c++ - 不要使用 Bazel 破坏共享库的名称
- python - 将图像加载为 TensorFlow 数据集并输入 Keras model.fit 的工作流程?
- java - 无法使用 Jenv 在 Mac OS 中更改 JDK
- pyspark - pyspark hive - 通过文本文件将 NULL 作为 DB null 插入
- ios - SwiftUI 视图首选项:overlayPreferenceValue 在复杂容器上使用时返回 nil
- python - Python - 将两个 API 值存储到变量中