继承者和装饰者

2024-04-23 19:43:25 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能解释一下为什么这会产生一个名称错误,其中类a找不到decorator\u仓库变量,即使它位于其父类Mixin的内部?你知道吗

NameError: name 'decorator_warehouse' is not defined

另外,如何获得所需的功能,即将decorator\u仓库放在一个不同的类中,而不是包含我希望装饰的功能的类中。你知道吗

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()

Tags: self功能objectdefcustomdecoratorwarehousemixin