|
|
|
|
|
by gergo_barany
709 days ago
|
|
You're right that you can't override __add__ for numbers, but the bytecode doesn't say this. The bytecode isn't specialized to numbers. It will call the __add__ operation on whatever object you give it. The interpreter will probably have a fast path in its implementation of the BINARY_OP instruction that checks for numbers. But that doesn't mean that the BINARY_OP instruction can only handle numbers. Example: >>> class foo(object):
... def __add__(x, y):
... print(f'"adding" {x} and {y} by returning {y}+1', x, y, y)
... return y + 1
...
>>> f = foo()
>>> f + 3
"adding" <__main__.foo object at 0x725f470c4e90> and 3 by returning 3+1 <__main__.foo object at 0x725f470c4e90> 3 3
4
>>> add_five(f)
"adding" <__main__.foo object at 0x725f470c4e90> and 5 by returning 5+1 <__main__.foo object at 0x725f470c4e90> 5 5
6
(Not sure why there's extra garbage printed, my Python is a bit rusty.) |
|