[英]Python commutative operator override
Hi I was wondering if there is a way to do a symmetric operator override in Python. 嗨,我想知道是否有一种方法可以在Python中进行对称运算符覆盖。 For example, let's say I have a class:
例如,假设我有一个课程:
class A:
def __init__(self, value):
self.value = value
def __add__(self, other):
if isinstance(other, self.__class__):
return self.value + other.value
else:
return self.value + other
Then I can do: 然后我可以做:
a = A(1)
a + 1
But if I try: 但是,如果我尝试:
1 + a
I get an error. 我得到一个错误。 Is there a way to override the operator add so that 1 + a will work?
有没有一种方法可以覆盖运算符的加法,以便1 + a起作用?
Just implement an __radd__
method in your class. 只需在您的类中实现
__radd__
方法即可。 Once the int class can't handle the addition, the __radd__
if implemented, takes it up. 一旦int类无法处理加法,
__radd__
如果已实现)将对其进行处理。
class A(object):
def __init__(self, value):
self.value = value
def __add__(self, other):
if isinstance(other, self.__class__):
return self.value + other.value
else:
return self.value + other
def __radd__(self, other):
return self.__add__(other)
a = A(1)
print a + 1
# 2
print 1 + a
# 2
For instance, to evaluate the expression x - y, where y is an instance of a class that has an
__rsub__()
method,y.__rsub__(x)
is called ifx.__sub__(y)
returnsNotImplemented
.例如,要评估表达式x-y,其中y是具有
__rsub__()
方法的类的实例,如果x.__sub__(y)
返回NotImplemented
则会调用y.__rsub__(x)
。
Same applies to x + y
. 同样适用于
x + y
。
On a side note, you probably want your class to subclass object
. 附带说明一下,您可能希望您的类对
object
进行子类化。 See What is the purpose of subclassing the class "object" in Python? 请参见在Python中将类“对象”子类化的目的是什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.