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?

3
  • 2
    Because magic methods are never looked up on the instance, see docs.python.org/3/reference/datamodel.html#special-lookup Commented Nov 3, 2018 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):? Commented Nov 3, 2018 at 18:55
  • 1
    @Bazingaa: absolutely. self is not a reserved name, it's just a convention. Commented Nov 3, 2018 at 18:56

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.