Python radd能以任何顺序处理操作数吗?
我希望我的Python radd能以任何顺序处理操作数吗?,python,class,python-3.x,operator-overloading,Python,Class,Python 3.x,Operator Overloading,我希望我的分数类在被添加到浮点或整数时作为浮点工作,这样我就可以自然地使用它执行操作,但它只在分数是最右边的操作数时工作。有没有一种方法可以让它以任何顺序与操作数一起工作,或者我应该重写另一个我没有学过的方法 代码(我想变量名很容易解释): 1+分数(1,2)按其应有的方式返回1.5,但分数(1,2)+1提高: Traceback (most recent call last): File "/Users/mac/Desktop/programming/python/fraction.py"
分数
类在被添加到浮点或整数时作为浮点工作,这样我就可以自然地使用它执行操作,但它只在分数
是最右边的操作数时工作。有没有一种方法可以让它以任何顺序与操作数一起工作,或者我应该重写另一个我没有学过的方法
代码(我想变量名很容易解释):
1+分数(1,2)
按其应有的方式返回1.5
,但分数(1,2)+1
提高:
Traceback (most recent call last):
File "/Users/mac/Desktop/programming/python/fraction.py", line 86, in <module>
print(my_fraction + 1)
File "/Users/mac/Desktop/programming/python/fraction.py", line 28, in __add__
new_den = self.den * target.den
AttributeError: 'int' object has no attribute 'den'
回溯(最近一次呼叫最后一次):
文件“/Users/mac/Desktop/programming/python/fraction.py”,第86行,在
打印(我的分数+1)
文件“/Users/mac/Desktop/programming/python/fraction.py”,第28行,添加__
new_den=self.den*target.den
AttributeError:“int”对象没有属性“den”
仅适用于执行value+self
时。如果要处理self+值
,则需要重载
因为它们都做相同的事情,所以您可以:
def __add__(self, target):
if isinstance(target, (int, float)):
return target + self.num/self.den
__radd__ = __add__
记住这一点的一个简单方法是将\uuuu radd\uuuu
中的r
视为代表“右”。因此,当类位于+
操作符的右侧时,您可以使用\uuu radd\uuu
另外,你会注意到我以前做过打字检查。除了更干净之外,大多数Python程序员都喜欢这种方法,并且在中明确提倡这种方法。非常感谢,这种方法非常有效!关于
isinstance的数据也很好,我不知道。如果你想让这个类在Python 2上工作,你需要将self.num和/或self.den转换为float,例如,返回target+float(self.num)/self.den
。FWIW,在我的分数类中,我将整数提升为分数,但我想用户自己显式地转换整数是很容易的。顺便说一句,如果你想把浮动转换成rational形式,你可以使用一些技术。
def __add__(self, target):
if isinstance(target, (int, float)):
return target + self.num/self.den
__radd__ = __add__