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

クラスにすることもできますが、記述子プロトコルを使用する必要があります

 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これは、decoratedメソッドのインスタンスではなく、decoratingクラスのインスタンスを参照するものが1つだけ渡されるためです。

于 2010-09-13T21:40:20.530 に答える
1

私の以前の回答は急いで作成されました。デコレーターを書きたい場合は、モジュールwrapsから実際に使用する必要があります。functoolsそれはあなたのために難しいものを処理します。

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 に答える