I have a problem with the implementation of a decorator applied at this metaclass decorator I wrote:
def decorateAll(decorator):
class MetaClassDecorator(type):
def __new__(meta, classname, supers, classdict):
for name, elem in classdict.items():
if type(elem) is FunctionType:
classdict[name] = decorator(classdict[name])
return type.__new__(meta, classname, supers, classdict)
return MetaClassDecorator
This is the class in which I have used the metaclass:
class Account(object, metaclass=decorateAll(Counter)):
def __init__(self, initial_amount):
self.amount = initial_amount
def withdraw(self, towithdraw):
self.amount -= towithdraw
def deposit(self, todeposit):
self.amount += todeposit
def balance(self):
return self.amount
Everything seems to work great when I pass to the decorator metaclass a decorator implemented like this:
def Counter(fun):
fun.count = 0
def wrapper(*args):
fun.count += 1
print("{0} Executed {1} times".format(fun.__name__, fun.count))
return fun(*args)
return wrapper
But when I use a decorator implemented in this way:
class Counter():
def __init__(self, fun):
self.fun = fun
self.count = 0
def __call__(self, *args, **kwargs):
print("args:", self, *args, **kwargs)
self.count += 1
print("{0} Executed {1} times".format(self.fun.__name__, self.count))
return self.fun(*args, **kwargs)
I got this error:
line 32, in __call__
return self.fun(*args, **kwargs)
TypeError: __init__() missing 1 required positional argument: 'initial_amount'
Why? Using the two decorators implementation with others function doesn't show me problems. I think that the problem is tied to the fact that the methods to which I'm trying to decorate are class methods. Am I missing something?