2

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.

winwin
  • 958
  • 7
  • 25
  • 1
    you can only overload the class methods at runtime but not the methods of the instances of that class – DevLounge Mar 21 '21 at 23:54
  • Do you actually want `a` to have a `__str__` that works differently from other instances of the `A` class? If so, why? Or do you only want to change the class' `__str__` after the fact? – Karl Knechtel Mar 21 '21 at 23:58
  • Does https://stackoverflow.com/questions/972/adding-a-method-to-an-existing-object-instance answer your question? – TigerhawkT3 Mar 22 '21 at 00:01

2 Answers2

3

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'
Samwise
  • 68,105
  • 3
  • 30
  • 44
2

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
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97