I hope someone can answer this that has a good deep understanding of Python :)
Consider the following code:
>>> class A(object): ... pass ... >>> def __repr__(self): ... return "A" ... >>> from types import MethodType >>> a = A() >>> a <__main__.A object at 0x00AC6990> >>> repr(a) '<__main__.A object at 0x00AC6990>' >>> setattr(a, "__repr__", MethodType(__repr__, a, a.__class__)) >>> a <__main__.A object at 0x00AC6990> >>> repr(a) '<__main__.A object at 0x00AC6990>' >>>
Notice how repr(a) does not yield the expected result of "A" ? I want to know why this is the case and if there is a way to achieve this...
I contrast, the following example works however (Maybe because we're not trying to override a special method?):
>>> class A(object): ... def foo(self): ... return "foo" ... >>> def bar(self): ... return "bar" ... >>> from types import MethodType >>> a = A() >>> a.foo() 'foo' >>> setattr(a, "foo", MethodType(bar, a, a.__class__)) >>> a.foo() 'bar' >>>
3) An instance method cannot override a static method, and a static method cannot hide an instance method. For example, the following program has two compiler errors.
Instance method are methods which require an object of its class to be created before it can be called. To invoke a instance method, we have to create an Object of the class in which the method is defined.
In Python method overriding occurs by simply defining in the child class a method with the same name of a method in the parent class. When you define a method in the object you make this latter able to satisfy that method call, so the implementations of its ancestors do not come in play.
A method declared final cannot be overridden. A method declared static cannot be overridden but can be re-declared. If a method cannot be inherited, then it cannot be overridden. A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final.
Python usually doesn't call the special methods, those with name surrounded by __
on the instance, but only on the class. (Although this is an implementation detail, it's characteristic of CPython, the standard interpreter.) So there's no way to override __repr__()
directly on an instance and make it work. Instead, you need to do something like so:
class A(object): def __repr__(self): return self._repr() def _repr(self): return object.__repr__(self)
Now you can override __repr__()
on an instance by substituting _repr()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With