是的。实际上,从您似乎的意思来看,实际上没有一种方法可以编写无法访问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>