Python 使用decorator创建类

Python 使用decorator创建类,python,decorator,fsm,Python,Decorator,Fsm,我用python实现了一个有限状态机。这是可行的,但实现状态需要编写不必要的代码 class State: def __init__(self): <do something> def __call__(): <do something different> class ConcreteState(State): def __init__(self): super().__init__()

我用python实现了一个
有限状态机
。这是可行的,但实现状态需要编写不必要的代码

class State:
    def __init__(self):
        <do something>

    def __call__():
       <do something different>

class ConcreteState(State):
    def __init__(self):
       super().__init__()

    def __call__():
        super().__call__()
       <do concrete state implementation>

这很难看,但由于装饰器可以返回任何东西,因此它可以返回类而不是函数:

def StateDecorator(fn):
    class cls(State):
        def __call__(self):
            super().__call__()
            fn(self)
    return cls

@StateDecorator
def concreteState(self):
    print("cc", self)

concreteState
<class '__main__.cls'>
def状态装饰器(fn): 类别cls(州): 定义呼叫(自我): 超级() fn(自我) 返回cls @状态装饰器 状态(自我): 打印(“抄送”,自我) 具体状态 请注意,这可能会混淆您正在使用的任何静态分析工具。

类似于:

def StateDecorator(implementation):
    class StateImplementation(State):
        def __call__(self):
            super().__call__()
            implementation()
    return StateImplementation
def StateDecorator(implementation):
    class StateImplementation(State):
        def __call__(self):
            super().__call__()
            implementation()
    return StateImplementation