Python console:
~/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'
>>>
Why do I have to add the __mul__
function to do multiplication instead of just 6 + 6
?
I hope your answers help me.
2