简体   繁体   English

为内置实例和类实例定义运算符

[英]Define operator for built-in and class instance

In Python you can override an operation for your class (say, addition) by defining __add__ . 在Python中,您可以通过定义__add__来覆盖类的操作(例如加法)。 This will make it possible add class instance with other values/instances, but you can't add built-ins to instances: 这将使添加具有其他值/实例的类实例成为可能,但是您不能将内置实例添加到实例中:

foo = Foo()
bar = foo + 6 # Works
bar = 6 + foo # TypeError: unsupported operand type(s) for +: 'int' and 'Foo'

Is there any way to make enable this? 有什么办法可以做到这一点?

当实例在右侧时__radd__(self, other)必须定义方法__radd__(self, other)来覆盖运算符+

You cannot override the + operator for integers. 您不能为整数覆盖+运算符。 What you should do is to override the __radd__(self, other) function in the Foo class only . 您应该做的是仅覆盖Foo类中__radd__(self, other)函数。 The self variable references a Foo instance, not an integer, and the other variable references the object on the left side of the + operator. self变量引用一个Foo实例,而不是整数, other变量引用+运算符左侧的对象。 When bar = 6 + foo is evaluated, the attempt to evaluate 6.__add__(foo) fails and then Python tries foo.__radd__(6) (reverse __add__ ). 当计算bar = 6 + foo ,尝试评估6.__add__(foo)失败,然后Python尝试foo.__radd__(6) (反向__add__ )。 If you override __radd__ inside Foo , the reverse __add__ succeeds, and the evaluation of 6 + foo is the result of foo.__radd__(6) . 如果您在Foo重写__radd__ ,则反向__add__成功,并且对6 + foo的求值是foo.__radd__(6)

def __radd__(self, other):
   return self + other

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM