I tried to conditionally create the
__str__
method in a python class, as recommended here and here and I understand that is is not recommended to do this. But for my understanding, doing:
from types import MethodType
def str_fcn(self):
return self.a
class A(object):
def __init__(self, a=None):
if a is not None:
self.a = a
self.__str__ = MethodType(str_fcn, self)
self.test = MethodType(str_fcn, self)
a = A(a="name")
print(a)
print(a.test())
Does not seem to work for magic methods. The last print call at the end prints "name" as I expect, but the first uses the default string representation. Why?