编程语言
首页 > 编程语言> > python – 创建可以看到当前类方法的装饰器

python – 创建可以看到当前类方法的装饰器

作者:互联网

你能在类中创建一个装饰器来查看类方法和变量吗?

这里的装饰者没有看到:self.longcondition()

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

    # decorator that will see the self.longcondition ???
    class canRun(object):
            def __init__(self, f):
                self.f = f

            def __call__(self, *args):
                if self.longcondition(): # <-------- ???
                    self.f(*args)

    # this is supposed to be a very long condition :)
    def longcondition(self):
        return isinstance(self.name, str)

    @canRun # <------
    def run(self, times):
        for i in xrange(times):
            print "%s. run... %s" % (i, self.name)

解决方法:

你可以让它成为一个类,但你需要使用描述符协议

 import types

 class canRun(object):
    def __init__(self, f):
        self.f = f
        self.o = object  # <-- What the hell is this about? 

    def __call__(self, *args):
        if self.longcondition():
            self.f(*args)

    def __get__(self, instance, owner):
         return types.MethodType(self, instance)

当您想使用__call__方法使用类实例修饰类方法时,总是需要使用描述符.这样做的原因是只传递一个self,它引用了装饰类的实例而不是装饰方法的实例.

标签:python,decorator,class-method
来源: https://codeday.me/bug/20190526/1158074.html