创建可以看到当前类方法的装饰器 [英] Create decorator that can see current class method

查看:85
本文介绍了创建可以看到当前类方法的装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以在一个类中创建一个装饰器,该装饰器将看到类的方法和变量吗?

Can you create a decorator inside a class that will see the classes methods and variables?

这里的装饰器看不到:self.longcondition()

The decorator here doesnt see: 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)


推荐答案

您可以将其作为一个类,但需要使用描述符协议

You can have it be a class but you need to use the descriptor protocol

 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 传入,它引用装饰类的实例,而不是装饰方法的实例。

You always need to use a descriptor when you want to decorate class methods with a class instance using the __call__ method. The reason for this is that there will only be one self passed in which refers to the instance of the decorating class and not the instance of the decorated method.

这篇关于创建可以看到当前类方法的装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆