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

前端 未结 4 840
滥情空心
滥情空心 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:09

    You've sort of answered the question in asking it: what argument would you expect to get as self if you call SubSystem.UpdateGUI? There isn't an obvious instance that should be passed to the decorator.

    There are several things you could do to get around this. Maybe you already have a subSystem that you've instantiated somewhere else? Then you could use its decorator:

    subSystem = SubSystem()
    subSystem.UpdateGUI(...)
    

    But maybe you didn't need the instance in the first place, just the class SubSystem? In that case, use the classmethod decorator to tell Python that this function should receive its class as the first argument instead of an instance:

    @classmethod
    def UpdateGUI(cls,...):
        ...
    

    Finally, maybe you don't need access to either the instance or the class! In that case, use staticmethod:

    @staticmethod
    def UpdateGUI(...):
        ...
    

    Oh, by the way, Python convention is to reserve CamelCase names for classes and to use mixedCase or under_scored names for methods on that class.

提交回复
热议问题