在decorator类中,访问包含装饰方法的类的实例

Ing*_*her 9 python decorator

我有以下装饰器,它在@saveconfig调用装饰的方法后保存配置文件:

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"
Run Code Online (Sandbox Code Playgroud)

我在下面的类中使用这个装饰器.createkvm调用该方法后,配置对象self.cfg应保存在装饰器中:

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"
Run Code Online (Sandbox Code Playgroud)

我的问题是我需要访问self.cfg装饰器内的对象变量saveconfig.第一个天真的方法是向装饰器添加一个参数来保存对象@saveconfig(self),但这不起作用.

如何在装饰器中访问方法主机的对象变量?我是否必须在同一个类中定义装饰器才能获得访问权限?

Sve*_*ach 11

您必须使您的装饰器类表现为描述符才能访问该实例:

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
Run Code Online (Sandbox Code Playgroud)

您的代码将object作为第一个参数self.f(),它应该通过pbtools实例.