cuốn sách gpt4 ai đã làm

Python:使自定义对象与标准类型相乘/相加

In lại Tác giả: Walker 123 更新时间:2023-11-28 21:15:45 30 4
mua khóa gpt4 Nike

我知道可以创建 object.__mul__(self, other)启用两个对象的自定义乘法的方法。然而,正如 python 文档中所解释的那样,

to evaluate the expression x + y, where x is an instance of a class that has an __add__() method, x.__add__(y) is called.

是否有可能以任何方式允许以相反的顺序自定义对象的乘法/加法,即 y + x,其中 x 是我们拥有的一个实例控制,并且 y 是标准类型,例如漂浮物?

câu trả lời hay nhất

是的,这是可能的。

事实上,在您正在查看的同一文档中仅向下半页解释了它。您只需定义一个 __rmul__(self, other) phương pháp.

正如文档所说:

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. 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.

所以:

>>> class Thingy(object):
... def __mul__(self, other):
... print('mul', other)
... def __rmul__(self, other):
... print('rmul', other)
>>> thingy = Thingy()
>>> thingy * 3
mul 3
>>> 3 * thingy
rmul 3

如果相关,请参阅关于子类的注释;对于内置类型,通常不是。

另请注意,没有 __rlt__ , __req__等,但适用相同的规则;只是反射是__gt__ , __eq__等您已经定义的方法。

关于Python:使自定义对象与标准类型相乘/相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29711773/

30 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress