为什么我添加__add__函数时不能使用*?

问题描述 投票:0回答:1

Python 控制台:

~/PythonProject$ python
Python 3.10.13 (main, Aug 24 2023, 12:59:26) [GCC 13.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> class Six:
...     def __repr__(self):
...         return '<Six>'
...     def __int__(self):
...         return 6
...     def __add__(self, other):
...         return int(self) + int(other)
...     __radd__ = __add__
... 
>>> six = Six()
>>> six
<Six>
>>> six + 1
7
>>> 1 + six
7
>>> six + Six()  # Addition OK
12
>>> six * 2  # Why Python doesn't use 6 + 6?
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'Six' and 'int'
>>> 

为什么我必须添加

__mul__
函数来进行乘法运算,而不仅仅是
6 + 6
? 希望您的回答对我有帮助。

python
1个回答
0
投票

Python 唯一的工作就是将

x + y
翻译为
x.__add__(y)
y.__radd__(x)
。如果您的类型恰好是
x + x == 2 * x
,您还需要定义
__mul__
来表明这一事实; Python 不假设它。

例如,您可以定义

def __mul__(self, other):
    if other == 2:
        return self + self
    ...

__rmul__ == mul

更复杂的定义可以处理

other
的任意整数值,拒绝
float
other
值(或与加法分开定义操作)等。

© www.soinside.com 2019 - 2024. All rights reserved.