简体   繁体   中英

Issues with class methods and attributes

I have a class with a few methods such as :

class Module:

  def __init__(self, name):
    self.name = name
    self.finite_state_machine = None

  def fsm(self, call_stack, module_name):
    pass
    # returns the finite state machine of a given module 

  def reading_file(path="default_path"):
    pass
    # opens and reads a file, return a list of line used for the next method

  def modules_dictionnary(self, lines):
    pass
    # returns the dictionnary of the modules
 
  def message_stack(lines, modules_dictionnary):
    pass
    # returns the call_stack the fsm method needs

The thing is I'm getting confused with methods, self keyword, classmethods, staticmethods etc

I would like for each class object say m = Module('Alpha') to have :

  • a name (different for each object)
  • a module dictionnary and a call_stack (shared among each object of this class
  • a finite state machine (different for each object)

I tried running this in the builder : self.fsm = self.fsm(message_stack(reading_file(), modules), modules_dictionary(reading_file())) but it doesn't seem to work. I think I'm missing smething on the role of attributes and methods etc

You can initialise dictionary and a call_stack in init function. They will be shared among all the objects of class. And for different value for each object you can create setter functions for name and final state machine and call them with required value. Something like this:

class Module:

 def __init__(self, dictionary, call_state):
     self.dictionary = dictionary
     self.call_state = call_state
     self.finite_state_machine = None
     self.name = None
 def set_name(self, name):
     self.name = name
     
 def set_fsm(self, fsm):
     self.finite_state_machine = fsm
     
dict_v = {}
call_state = ""
obj = Module(dict_v, call_state)
obj.set_name("xyq")
obj.set_fsm("testing")

This answer sets the focus on the definition of the dictionary on class level.

class Module:
    dictionary = {}

    def __init__(self, name):
        self.name = name

    def add_to_dictionary(self, key, value):
        Module.dictionary[key] = value


m1 = Module('a')
m1.add_to_dictionary('Monty', 'Python')
m2 = Module('b')
print(m2.dictionary)

This will give you {'Monty': 'Python'} .

You could even drop the add_to_dictionary method.

m2.dictionary['Eric'] = 'Idle'

# let's look at the content
print(m1.name)
print(m1.dictionary)
print(m2.name)
print(m2.dictionary)

With the result

a
{'Monty': 'Python', 'Eric': 'Idle'}
b
{'Monty': 'Python', 'Eric': 'Idle'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM