11

次のように定義されたクラスがあります。

class SomeViewController(BaseViewController):
    @requires('id', 'param1', 'param2')
    @ajaxGet
    def create(self):
        #do something here

次のようなデコレータ関数を書くことは可能ですか?

  1. 引数のリスト、場合によっては kwargs を受け取り、
  2. デコレートするメソッドが定義されているクラスのインスタンスにアクセスしますか?

したがって、 @ajaxGet デコレーターの場合、チェックする必要がある値を含む属性がself呼び出されます。type

ありがとう

4

1 に答える 1

16

はい。実際、あなたが意味しているように見える意味で、にアクセスできないデコレータを書く方法は実際にはありませself。装飾された関数は元の関数をラップするため、少なくともその関数が受け入れる引数 (またはそれらを導出できるいくつかの引数) を受け入れる必要があります。そうしないと、基になる関数に正しい引数を渡すことができません。

これを行うために特別なことは何も必要ありません。普通のデコレータを書くだけです:

def deco(func):
    def wrapper(self, *args, **kwargs):
        print "I am the decorator, I know that self is", self, "and I can do whatever I want with it!"
        print "I also got other args:", args, kwargs
        func(self)
    return wrapper

class Foo(object):
    @deco
    def meth(self):
        print "I am the method, my self is", self

次に、それを使用できます:

>>> f = Foo()
>>> f.meth()
I am the decorator, I know that self is <__main__.Foo object at 0x0000000002BCBE80> and I can do whatever I want with it!
I also got other args: () {}
I am the method, my self is <__main__.Foo object at 0x0000000002BCBE80>
>>> f.meth('blah', stuff='crud')
I am the decorator, I know that self is <__main__.Foo object at 0x0000000002BCBE80> and I can do whatever I want with it!
I also got other args: (u'blah',) {'stuff': u'crud'}
I am the method, my self is <__main__.Foo object at 0x0000000002BCBE80>
于 2013-03-04T07:16:33.507 に答える