有人可以为我澄清为什么这会产生一个名称错误,其中A类找不到decorator_warehouse变量,即使它位于其父类Mixin中?
NameError: name 'decorator_warehouse' is not defined
另外,我怎样才能获得所需的功能,即将decorator_warehouse放在一个不同的类中,而不是包含我想要装饰的函数的类。
class DecoratorWarehouse(object):
"""Object hosts a large number of custom decorators"""
def custom_decorator_A(self, func):
def wrapper(*args, **kwargs):
print "doing stuff before call"
res = func(*args, **kwargs)
print "doing stuff after call"
return res
return wrapper
class Mixin(object):
decorator_warehouse = DecoratorWarehouse()
class A(Mixin):
@decorator_warehouse.custom_decorator_A
def doing_stuff(self):
print "Doing some stuff"
a = A()
a.doing_stuff()
答案 0 :(得分:0)
class A(Mixin):
@Mixin.decorator_warehouse.custom_decorator_A
def doing_stuff(self):
print "Doing some stuff"