实例方法可以是另一个不同类的方法的装饰器

时间:2017-08-02 20:58:19

标签: python decorator

class Foo():
    def __init__(self, a):
        self.a = a 


    def decorator(self, method):
        def wrapper(*args, **kws):
            if self.a == 'a' :
                return method(*args, **kws)  
            else:
                print ('cannot find attr a') 
            return wrapper    

class Bar():
    def __init__(self, b):
        self.b = b
        self.foo = Foo(b)

    @self.foo.decorator
    def method(self):
        print (self.b) 

bar = Bar('a')
bar.method()   

在这种情况下,我想使用实例方法来装饰另一个类中的另一个方法。每个要装饰的装饰器或方法都必须访问一些实例变量。所以它们不能与给定的类分开,甚至不能成为静态方法。当然,我的代码不起作用,因为我没有在@句子中定义'self'。任何人都可以给我一些建议来实现它,或者这只是一条死胡同?

0 个答案:

没有答案
相关问题