【问题标题】:Create class with decorator使用装饰器创建类
【发布时间】:2012-11-05 08:46:30
【问题描述】:

我在 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>

【问题讨论】:

    标签: python decorator fsm


    【解决方案1】:

    类似:

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

    【讨论】:

      【解决方案2】:

      这很丑,但是由于装饰器可以返回任何东西,所以它可以返回一个类而不是一个函数:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-28
        • 1970-01-01
        • 2014-02-13
        • 2020-09-05
        • 2017-11-16
        • 2021-07-16
        • 2014-01-14
        • 1970-01-01
        相关资源
        最近更新 更多