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!
CodePudding user response:
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.
CodePudding user response:
In addition to @AKX solution, you can also use decoration and decorate your function:
def double_size(fn):
def wrapper():
return fn() * 2
return wrapper
bear.size()
bear.size = double_size(bear.size)
bear.size()