Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't __repr__ be an attribute defined in __init__? [duplicate]

Tags:

python

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?

like image 467
CodeNStuff Avatar asked Dec 11 '25 02:12

CodeNStuff


1 Answers

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

like image 118
AKX Avatar answered Dec 13 '25 15:12

AKX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!