用装饰器创建类

时间:2012-11-05 08:46:31

标签: python decorator fsm

我在python中实现了Finite state machine。这有效,但实现状态需要编写不必要的代码。

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>

是否可以制作decorator以实现具体状态,如下例所示?

@StateDecorator
def concreteState():
   <do concrete state implementation>

2 个答案:

答案 0 :(得分:2)

类似的东西:

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

答案 1 :(得分:1)

这很难看,但是因为装饰者可以返回任何东西,所以它可以返回一个类而不是一个函数:

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'>

请注意,这可能会混淆您正在使用的任何静态分析工具。

相关问题