Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding special methods on an instance

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' >>> 
like image 882
James Mills Avatar asked Apr 29 '12 22:04

James Mills


People also ask

Can you override an instance method?

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.

What is a special instance method in a class?

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.

How do you override a method from a different class in Python?

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.

Which method Cannot be overridden in Java?

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.


1 Answers

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().

like image 181
kindall Avatar answered Sep 24 '22 14:09

kindall