All Courses

Design Patterns State in Python

Radhika Sharma

3 years ago

Design Patterns State in Python | insideAIML
Table of Contents
  • Implementation of the state pattern?
         Python provides a module for the state machines, which are implemented using subclasses, which are derived from a specified state machine class. The methods are state independent and cause transition declared using decorators.

Implementation of the state pattern?

Let’s take a simple example to see the implantation of the state pattern.
class ComputerState(object):

   name = "state"
   allowed = []

   def switch(self, state):
      """ Switch to new state """
      if in self.allowed:
         print('Current:',self,' => switched to new state',
         self.__class__ = state
         print ('Current:',self,' => switching to',,'not possible.')

   def __str__(self):

class Off(ComputerState):
   name = "off"
   allowed = ['on']

class On(ComputerState):
   """ State of being powered on and working """
   name = "on"
   allowed = ['off','suspend','hibernate']

class Suspend(ComputerState):
   """ State of being in suspended mode after switched on """
   name = "suspend"
   allowed = ['on']

class Hibernate(ComputerState):
   """ State of being in hibernation after powered on """
   name = "hibernate"
   allowed = ['on']

class Computer(object):
   """ A class representing a computer """
   def __init__(self, model='HP'):
      self.model = model
      # State of the computer - default is off.
      self.state = Off()
   def change(self, state):
      """ Change state """

if __name__ == "__main__":
   comp = Computer()
Output | InsideAIML
Like the Blog, then Share it with your friends and colleagues to make this AI community stronger. 
To learn more about nuances of Artificial Intelligence, Python Programming, Deep Learning, Data Science and Machine Learning, visit our insideAIML blog page.
Keep Learning. Keep Growing. 

Submit Review