我可以重载运算符的第一个参数是内置类型吗?例如,我有一个变量类:
class Variable:
def __init__(self, value):
self.value = value
def __add__(self, other):
if isinstance(other, self.__class__):
return self.value + other.value
elif isinstance(other, (int, float, complex)):
return self.value + other
else:
raise ValueError('Wrong data type')
我可以做这个:
>>> x = Variable(3)
>>> y = Variable(4)
>>> x + y
7
>>> x + 1
4
但我不能改变顺序:
>>> 1 + x
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
1 + x
TypeError: unsupported operand type(s) for +: 'int' and 'Variable'
是否有可能使这项工作?
尝试添加另一个神奇的方法__radd__
:
class Variable:
def __init__(self, value):
self.value = value
def __add__(self, other):
if isinstance(other, self.__class__):
return self.value + other.value
elif isinstance(other, (int, float, complex)):
return self.value + other
else:
raise ValueError('Wrong data type')
def __radd__(self, other):
if isinstance(other, self.__class__):
return self.value + other.value
elif isinstance(other, (int, float, complex)):
return self.value + other
else:
raise ValueError('Wrong data type')
x = Variable(3)
print(1 + x)
这个__radd__
神奇的方法是reverse add 的缩写,它用于指定当这个类被添加到其他东西时做什么。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句