I'm trying to decorate class instances with new methods. But if the decorator adds a method from it's own self it gives me an error
TypeError: myMethod() takes 1 positional argument but 2 were given
To give a minimal example, say I have a class MyElement I cannot modify and a Decorator adding a method from itself to instances of MyElement
class MyElement(object):
def __init(self):
self._name = "MyElement"
class Decorator(object):
def myMethod(self):
print(self._name)
def decorate(self, element):
element.myMethod = MethodType(self.myMethod, element)
if __name__ == '__main__':
d = Decorator()
p = MyElement()
d.decorate(p)
p.myMethod()
This gives me the error above. Altough If I change decorate to this it works :
def decorate(self, element):
element.myMethod = MethodType(self.myMethod.__func__, element)
Could somebody explain what actually MethodType is doing? And why the func flag si necessary?