3 ms·
You can't actually override operator_plus in Python for numbers. Numbers in Python are magic for performance reasons. You can look at the Python bytecode to eas
by gizmo 2y ago
You can't actually override operator_plus in Python for numbers. Numbers in Python are magic for performance reasons. You can look at the Python bytecode to easily see this:
def add_five(a):
return a + 5
dis.dis(add_five)
And this returns something like:
LOAD FAST a
LOAD CONST 5
BINARY ADD
RETURN ACC
- gergo_barany 2y agoYou'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.)