3

You can emulate a method by dynamically assign a callable to an equally named attribute of your class. This basically works for common as well as for dunder methods. But the lambda version does not work as hook for the interpreter's mechanisms:

>>> class Foo:
...     def bar(self):
...         return 'bar'
...     def __repr__(self):
...         return 'repr'
... f = Foo()
>>> f.bar()
'bar'
>>> f.__repr__()
'repr'
>>> print(f)
repr

>>> class Foo:
...     def __init__(self):
...         self.bar = lambda: 'bar'
...         self.__repr__ = lambda: 'repr'
... f = Foo()
>>> f.bar()
'bar'
>>> f.__repr__()
'repr'
>>> print(f)
<__main__.Foo object at 0x000000FC7A879EB8>

Why is that?

CodeNStuff
  • 266
  • 3
  • 11
  • "You can emulate a method by ..." Your assumption is false; you are merely storing callables as attributes. Note how your ``lambda`` s do *not* receive a ``self`` parameter. They also do not work for dunder methods at all -- try calling ``repr(f)`` instead of ``f.__repr__()``. – MisterMiyagi Oct 18 '19 at 10:55

1 Answers1

1

Because the C function PyObject_Repr() only looks at the repr declared by the object's type, not in the object's dict.

AKX
  • 152,115
  • 15
  • 115
  • 172