问题描述
我有以下装饰器,该装饰器在用 @saveconfig
装饰的方法被调用后保存配置文件:
I have the following decorator, which saves a configuration file after a method decorated with @saveconfig
is called:
class saveconfig(object):
def __init__(self, f):
self.f = f
def __call__(self, *args):
self.f(object, *args)
# Here i want to access "cfg" defined in pbtools
print "Saving configuration"
我在下面的类中使用此装饰器。调用方法 createkvm
之后,配置对象 self.cfg
应该保存在装饰器中:
I'm using this decorator inside the following class. After the method createkvm
is called, the configuration object self.cfg
should be saved inside the decorator:
class pbtools()
def __init__(self):
self.configfile = open("pbt.properties", 'r+')
# This variable should be available inside my decorator
self.cfg = ConfigObj(infile = self.configfile)
@saveconfig
def createkvm(self):
print "creating kvm"
我的问题是我需要访问装饰器 saveconfig
中的对象变量 self.cfg
。第一种幼稚的方法是向装饰器添加一个参数,该装饰器保存对象,例如 @saveconfig(self)
,但这是行不通的。
My problem is that i need to access the object variable self.cfg
inside the decorator saveconfig
. A first naive approach was to add a parameter to the decorator which holds the object, like @saveconfig(self)
, but this doesn't work.
如何访问装饰器内部方法主机的对象变量?我是否必须在同一类中定义装饰器才能访问?
How can I access object variables of the method host inside the decorator? Do i have to define the decorator inside the same class to get access?
推荐答案
您必须让装饰器类表现为以能够访问实例:
You have to make your decorator class behave as a descriptor to be able to access the instance:
class saveconfig(object):
def __init__(self, f):
self.f = f
def __get__(self, instance, owner):
def wrapper(*args):
print "Saving configuration"
print instance.cfg
return self.f(instance, *args)
return wrapper
您的代码将对象
作为第一个参数传递给 self.f ()
,它应应该传递 pbtools
实例。
Your code passes object
as first parameter to self.f()
, where it should pass the pbtools
instance.
这篇关于在装饰器类内部,访问包含装饰方法的类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!