Python类继承,attributeError

时间:2017-06-02 09:24:04

标签: python inheritance state-machine

我在Python中编写了一个StateMachine类,因此可以从中继承。 它的逻辑按预期工作,但我可以从名为self.data的派生State类中的StateMachine访问属性StateMachineTest

生成以下错误:

Traceback (most recent call last):
File "/home/nbout/work/python/state_machine/main.py", line 68, in 
   main()
File "/home/nbout/work/python/state_machine/main.py", line 59, in main
   test = StateMachineTest()
File "/home/nbout/work/python/state_machine/main.py", line 47, in __init__
   StateMachine.__init__(self, Started())
File "/home/nbout/work/python/state_machine/state_machine.py", line 17, in _init__
   self.current_state.on_enter(self)
File "/home/nbout/work/python/state_machine/main.py", line 16, in on_enter
   print("Started: data:{}".format(sm_test.data))
Started: on_enter
AttributeError: 'StateMachineTest' object has no attribute 'data'
Started: on_exit

state_machine.py

class State:

    def on_enter(self, state_machine):
        pass

    def on_exit(self, state_machine):
        pass


class StateMachine:

    def __init__(self, start_state):
        self.current_state = start_state

        self.current_state.on_enter(self)

    def __del__(self):
        self.current_state.on_exit(self)

    def set_state(self, state):

        self.current_state.on_exit(self)
        self.current_state = state
        self.current_state.on_enter(self)

main.py

from state_machine import StateMachine
from state_machine import State


class StateTest(State):
    def pause(self, state_machine_test):
        pass

    def start(self, state_machine_test):
        pass


class Started(StateTest):
    def on_enter(self, sm_test):
        print("Started: on_enter")
        print("Started: data:{}".format(sm_test.data))

    def on_exit(self, sm_test):
        print("Started: on_exit")

    def pause(self, sm_test):
        print("Started: pause")
        sm_test.set_state(Paused())

    def start(self, sm_test):
        print("Started: start")


class Paused(StateTest):
    def on_enter(self, sm_test):
        print("Paused: on_enter")

    def on_exit(self, sm_test):
        print("Paused: on_exit")

    def pause(self, sm_test):
        print("Paused: pause")

    def start(self, sm_test):
        print("Paused: start")
        sm_test.set_state(Started())


class StateMachineTest(StateMachine):

    def __init__(self):
        StateMachine.__init__(self, Started())
        self.data = 10

    def pause(self):
        self.current_state.pause(self)

    def start(self):
        self.current_state.start(self)


def main():

    test = StateMachineTest()

    test.start()
    test.pause()
    test.pause()
    test.start()


if __name__ == '__main__':
    main()

2 个答案:

答案 0 :(得分:0)

哇,这段代码实际上是不必要的复杂。

问题似乎是您在StateMachineTest类的Started中初始化__init__,以便在设置on_enter之前运行self.data

您可以通过将self.data的分配移到super调用之上来解决此问题,但更好的办法是简化继承层次结构。

答案 1 :(得分:0)

您的问题在于StateMachine.__init__(self, Started())要求self的{​​{1}}属性已经设置,但您只需将其设置为下一行(data)。切换这两行,然后再试一次!