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

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

    You need to use an instance of SubSystem to do your decorating or use a classmethod as kenny suggests.

    subsys = SubSystem()
    class DO(SubSystem):
        def getport(self, port):
            """Returns the value of Digital Output port "port"."""
            pass
    
        @subsys.UpdateGUI
        def setport(self, port, value):
            """Sets the value of Digital Output port "port"."""
            pass
    

    You decide which to do by deciding if you want all subclass instances to share the same GUI interface or if you want to be able to let distinct ones have distinct interfaces.

    If they all share the same GUI interface, use a class method and make everything that the decorator accesses a class instance.

    If they can have distinct interfaces, you need to decide if you want to represent the distinctness with inheritance (in which case you would also use classmethod and call the decorator on the subclasses of SubSystem) or if it is better represented as distinct instances. In that case make one instance for each interface and call the decorator on that instance.

提交回复
热议问题