pytransitions / transitions

A lightweight, object-oriented finite state machine implementation in Python with many extensions
MIT License
5.49k stars 525 forks source link

How to pass data in the case of inheriting from the Machine class? #606

Closed vba34520 closed 1 year ago

vba34520 commented 1 year ago

Install

pip install  transitions==1.16.0

It's okay.

from transitions import Machine

class Matter(object):
    def __init__(self):
        self.temp = 0

    def set_environment(self, event):
        self.temp = event.kwargs.get('temp', 0)

    def print_pressure(self):
        print(self.temp)

lump = Matter()
machine = Machine(lump, ['solid', 'liquid'], send_event=True, initial='solid')
machine.add_transition('melt', 'solid', 'liquid', before='set_environment')
lump.melt(temp=45)
lump.print_pressure()  # 45

I want to pass data in the case of inheriting from the Machine class like this, but it doesn't work. Thanks!

from transitions import Machine

class Matter(Machine):
    def __init__(self):
        self.temp = 0
        states = ['solid', 'liquid', 'gas']
        Machine.__init__(self, states=states, send_event=True, initial='solid')
        self.add_transition('melt', 'solid', 'liquid')

    def set_environment(self, event):
        self.temp = event.kwargs.get('temp', 0)

    def print_pressure(self):
        print(self.temp)

lump = Matter()
lump.melt(temp=45)
lump.print_pressure()  # 0