作为基类一部分的Python装饰器不能用于装饰继承类中的成员函数

Aph*_*hex 25 python inheritance ironpython decorator

Python装饰器使用起来很有趣,但由于参数传递给装饰器的方式,我似乎已经碰壁了.这里我有一个装饰器被定义为基类的一部分(装饰器将访问类成员,因此它将需要self参数).

class SubSystem(object):
    def UpdateGUI(self, fun): #function decorator
        def wrapper(*args):
            self.updateGUIField(*args)
            return fun(*args)
        return wrapper

    def updateGUIField(self, name, value):
        if name in self.gui:
            if type(self.gui[name]) == System.Windows.Controls.CheckBox:
                self.gui[name].IsChecked = value #update checkbox on ui 
            elif type(self.gui[name]) == System.Windows.Controls.Slider:
                self.gui[name].Value = value # update slider on ui 

        ...
Run Code Online (Sandbox Code Playgroud)

我省略了其余的实现.现在这个类是将继承它的各种SubSystems的基类 - 一些继承的类需要使用UpdateGUI装饰器.

class DO(SubSystem):
    def getport(self, port):
        """Returns the value of Digital Output port "port"."""
        pass

    @SubSystem.UpdateGUI
    def setport(self, port, value):
        """Sets the value of Digital Output port "port"."""
        pass
Run Code Online (Sandbox Code Playgroud)

我再次省略了函数实现,因为它们不相关.

简而言之,问题是虽然我可以通过将其指定为SubSystem.UpdateGUI来从继承类访问基类中定义的装饰器,但在尝试使用它时我最终会得到此TypeError:

unbound method UpdateGUI() must be called with SubSystem instance as first argument (got function instance instead)

这是因为我没有立即识别的方法将self参数传递给装饰器!

有没有办法做到这一点?或者我是否达到了Python中当前装饰器实现的限制?

ken*_*ytm 22

你需要做UpdateGUI一个@classmethod,并让你wrapper意识到self.一个工作的例子:

class X(object):
    @classmethod
    def foo(cls, fun):
        def wrapper(self, *args, **kwargs):
            self.write(*args, **kwargs)
            return fun(self, *args, **kwargs)
        return wrapper

    def write(self, *args, **kwargs):
        print(args, kwargs)

class Y(X):
    @X.foo
    def bar(self, x):
        print("x:", x)

Y().bar(3)
# prints:
#   (3,) {}
#   x: 3
Run Code Online (Sandbox Code Playgroud)