はい。実際、あなたが意味しているように見える意味で、にアクセスできないデコレータを書く方法は実際にはありません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>