python - Overriding special methods on an instance -
python - Overriding special methods on an instance -
i hope can reply has deep understanding of python :)
consider next code:
>>> class a(object): ... pass ... >>> def __repr__(self): ... homecoming "a" ... >>> types import methodtype >>> = a() >>> <__main__.a object @ 0x00ac6990> >>> repr(a) '<__main__.a object @ 0x00ac6990>' >>> setattr(a, "__repr__", methodtype(__repr__, a, a.__class__)) >>> <__main__.a object @ 0x00ac6990> >>> repr(a) '<__main__.a object @ 0x00ac6990>' >>>
notice how repr(a) not yield expected result of "a" ? want know why case , if there way accomplish this...
i contrast, next illustration works (maybe because we're not trying override special method?):
>>> class a(object): ... def foo(self): ... homecoming "foo" ... >>> def bar(self): ... homecoming "bar" ... >>> types import methodtype >>> = a() >>> a.foo() 'foo' >>> setattr(a, "foo", methodtype(bar, a, a.__class__)) >>> a.foo() 'bar' >>>
python doesn't phone call special methods, name surrounded __
on instance, on class, apparently improve performance. there's no way override __repr__()
straight on instance , create work. instead, need so:
class a(object): def __repr__(self): homecoming self._repr() def _repr(self): homecoming object.__repr__(self)
now can override __repr__()
on instance substituting _repr()
.
python metaprogramming
Comments
Post a Comment