1

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?

Robert
  • 725
  • 1
  • 7
  • 15
  • 2
    Because magic methods are never looked up on the instance, see https://docs.python.org/3/reference/datamodel.html#special-lookup – Martijn Pieters Nov 03 '18 at 18:54
  • @MartijnPieters: I am wondering if one can use `self` as the argument of a function outside the class like the OP did in his code for `def str_fcn(self):`? – Sheldore Nov 03 '18 at 18:55
  • 1
    @Bazingaa: absolutely. `self` is not a reserved name, it's just a convention. – Martijn Pieters Nov 03 '18 at 18:56

0 Answers0