Inside a decorator-class, access instance of the class which contains the decorated method
Posted
by
ifischer
on Stack Overflow
See other posts from Stack Overflow
or by ifischer
Published on 2011-02-13T22:50:01Z
Indexed on
2011/02/13
23:25 UTC
Read the original article
Hit count: 342
python
|decorators
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"
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"
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?
© Stack Overflow or respective owner