继承和装饰者

时间:2014-02-10 00:03:25

标签: python python-2.7 inheritance

有人可以为我澄清为什么这会产生一个名称错误,其中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()

1 个答案:

答案 0 :(得分:0)

在这里找到答案:Python decorators that are part of a base class cannot be used to decorate member functions in inherited classes

class A(Mixin):
    @Mixin.decorator_warehouse.custom_decorator_A
    def doing_stuff(self):
        print "Doing some stuff"