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

hug*_*o24 4 python decorator class-method

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

这里的装饰者没有看到: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)
Run Code Online (Sandbox Code Playgroud)

Wil*_*hen 5

没有必要将这个装饰器作为一个类来实现,并且不需要在Foo类的定义中实现它.以下就足够了:

def canRun(meth):
    def decorated_meth(self, *args, **kwargs):
        if self.longcondition():
            print 'Can run'
            return meth(self, *args, **kwargs)
        else:
            print 'Cannot run'
            return None
    return decorated_meth
Run Code Online (Sandbox Code Playgroud)

使用该装饰器似乎工作:

>>> Foo('hello').run(5)
Can run
0. run... hello
1. run... hello
2. run... hello
3. run... hello
4. run... hello
>>> Foo(123).run(5)
Cannot run
Run Code Online (Sandbox Code Playgroud)