Search code examples
pythonoverridinginstance

Overriding method of a class instance in Python


I have an instance bear of some unknown class with a method size that returns a number. So for example:

bear.size()

will do some calculation and return a number, let's say 3.

I want to override this method so it returns double whichever number it is, so bear.size() will return 6.

When I try to implement it I get a recursion error, since the new method calls itself. So when I run:

from types import MethodType

class Animal():
    def size(self):
        return 3
bear = Animal()

def new_size(self):
    return self.size() * 2

bear.size() # returns 3. 
bear.size = MethodType(new_size, bear)
bear.size() # should return 6.

I get RecursionError: maximum recursion depth exceeded. How should I overwrite the method?

Thanks!


Solution

  • You can stash the old implementation on the instance so you can call it in the overridden version.

    from types import MethodType
    
    
    class Animal:
        def size(self):
            return 3
    
    
    bear = Animal()
    
    
    def new_size(self):
        return self._old_size() * 2
    
    
    bear.size()  # returns 3.
    bear._old_size = bear.size
    bear.size = MethodType(new_size, bear)
    print(bear.size())  # should return 6.
    

    Alternately, call the unbound original method with self:

    from types import MethodType
    
    
    class Animal:
        def size(self):
            return 3
    
    
    bear = Animal()
    
    
    def new_size(self):
        return Animal.size(self) * 2
    
    
    bear.size()  # returns 3.
    bear.size = MethodType(new_size, bear)
    print(bear.size())  # should return 6.