Reputation: 1797
I would like to know, if there is a way to overload operators in Python in runtime. For instance:
class A:
pass
a = A()
a.__str__ = lambda self: "noice"
print(str(a))
The desired output is "noice"
, but the given code uses object
's implementation of the str
function instead, yielding something along the lines: <__main__.A object at 0x000001CAB2051490>
.
Why doesn't the code use my overriden implementation of the function overload?
Python version used is 3.9.2
.
Upvotes: 2
Views: 143
Reputation: 49320
You have to assign that function to the class, not an instance of the class.
>>> class A:
... pass
...
>>> a = A()
>>> a.__str__ = lambda x: 'hi'
>>> print(a)
<__main__.A object at 0x000000A4D16C1D30>
>>> A.__str__ = lambda x: 'hi'
>>> print(a)
hi
Upvotes: 2
Reputation: 71434
When you call str(a)
, it resolves to the equivalent of a.__class__.__str__(a)
, not a.__str__()
.
>>> A.__str__ = lambda self: "noice"
>>> str(a)
'noice'
Upvotes: 3