In Python you can override an operation for your class (say, addition) by defining __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 . The self
variable references a Foo
instance, not an integer, and the other
variable references the object on the left side of the + operator. When bar = 6 + foo
is evaluated, the attempt to evaluate 6.__add__(foo)
fails and then Python tries foo.__radd__(6)
(reverse __add__
). If you override __radd__
inside Foo
, the reverse __add__
succeeds, and the evaluation of 6 + foo
is the result of foo.__radd__(6)
.
def __radd__(self, other):
return self + other
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.