4

你能在一个可以看到类方法和变量的类中创建一个装饰器吗?

这里的装饰器没有看到: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)
4

3 回答 3

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

使用该装饰器似乎有效:

>>> 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
于 2010-09-13T21:08:55.297 回答
1

我之前的回答是仓促的。如果你想写一个装饰器,你应该真正wrapsfunctools模块中使用。它会为您处理困难的事情。

定义 canRun 装饰器的正确方法是:

from functools import wraps
def canRun(f):
  @wraps(f)
  def wrapper(instance, *args):
    if instance.longcondition():
      return f(instance, *args)
  return wrapper

canRun 函数应该在类之外定义。

于 2010-09-13T21:06:49.930 回答
1

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

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

于 2010-09-13T21:40:20.530 回答