gpt4 book ai didi

python - 当类实例位于右侧时,如何让我的类控制加法操作?

转载 作者:行者123 更新时间:2023-12-01 03:31:04 24 4
gpt4 key购买 nike

考虑我的类(class)mint

class mint(object):
def __init__(self, i):
self.i = i

def __add__(self, other):
o = other.i if isinstance(other, mint) else other
return mint(1 + self.i + o)

def __repr__(self):
return str(self.i)

它的设计目的是进行另一种加法。

a = mint(1)

a + 1 + 2

6

但是,当我的对象位于右侧时添加不起作用。

1 + a
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-519-8da568c0620a> in <module>()
----> 1 1 + a
TypeError: unsupported operand type(s) for +: 'int' and 'mint'
<小时/>

问题:如何修改我的类,以便 1 + a会起作用吗?

最佳答案

您可以使用__radd__ :

class mint(object):
def __init__(self, i):
self.i = i

def __add__(self, other):
o = other.i if isinstance(other, mint) else other
return mint(1 + self.i + o)

def __repr__(self):
return str(self.i)

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

a = mint(1)
print(1 + a)

输出:

3

以下是 Python 文档的解释:

These methods are called to implement the binary arithmetic operations (+, -, *, @, /, //, %, divmod(), pow(), **, <<, >>, &, ^, |) with reflected (swapped) operands. These functions are only called if the left operand does not support the corresponding operation and the operands are of different types. [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 if x.sub(y) returns NotImplemented.

关于python - 当类实例位于右侧时,如何让我的类控制加法操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40927447/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com