Python:如何从类装饰器内部访问被装饰类的实例?
这里有个例子可以说明我的意思:
class MyDecorator(object):
def __call__(self, func):
# At which point would I be able to access the decorated method's parent class's instance?
# In the below example, I would want to access from here: myinstance
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
class SomeClass(object):
##self.name = 'John' #error here
name="John"
@MyDecorator()
def nameprinter(self):
print(self.name)
myinstance = SomeClass()
myinstance.nameprinter()
我需要给这个类加上装饰器吗?
3 个回答
1
self这个参数是作为第一个参数传递的。另外,你的MyDecorator
其实是一个模拟函数的类。把它直接写成一个真正的函数会更简单。
def MyDecorator(method):
def wrapper(self, *args, **kwargs):
print 'Self is', self
return method(self, *args, **kwargs)
return wrapper
class SomeClass(object):
@MyDecorator
def f(self):
return 42
print SomeClass().f()
2
请注意,在这个上下文中,“self”的使用只是一个约定,方法只是把第一个参数当作对实例对象的引用:
class Example:
def __init__(foo, a):
foo.a = a
def method(bar, b):
print bar.a, b
e = Example('hello')
e.method('world')
8
class MyDecorator(object):
def __call__(self, func):
def wrapper(that, *args, **kwargs):
## you can access the "self" of func here through the "that" parameter
## and hence do whatever you want
return func(that, *args, **kwargs)
return wrapper
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。