Python decorators that are part of a base class cannot be used to decorate member functions in inherited classes

前端 未结 4 838
滥情空心
滥情空心 2020-12-28 14:59

Python decorators are fun to use, but I appear to have hit a wall due to the way arguments are passed to decorators. Here I have a decorator defined as part of a base class

4条回答
  •  心在旅途
    2020-12-28 15:19

    You need to make UpdateGUI a @classmethod, and make your wrapper aware of self. A working example:

    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
    

提交回复
热议问题