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!
bear.sizecreates a new, callable instance attribute (the value being a new bound method) that shadows the class attributeAnimal.size. Overriding methods on a per-instance basis doesn't really make sense.self.size. If you want to keep that, I guess you could useAnimal.size(self)but I question the wisdom of mucking with your instance like this in the first place