【发布时间】:2016-04-29 07:48:50
【问题描述】:
我在我写的这个元类装饰器上应用的装饰器的实现有问题:
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
这是我使用元类的类:
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
当我将一个这样实现的装饰器传递给装饰器元类时,一切似乎都很好:
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
但是当我使用以这种方式实现的装饰器时:
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)
我收到了这个错误:
line 32, in __call__
return self.fun(*args, **kwargs)
TypeError: __init__() missing 1 required positional argument: 'initial_amount'
为什么?将这两个装饰器实现与其他功能一起使用不会给我带来问题。我认为这个问题与我试图装饰的方法是类方法有关。我错过了什么吗?
【问题讨论】:
标签: python decorator metaclass class-method