Home > front end >  How to create a list of objects in python
How to create a list of objects in python

Time:05-09

I want to create a list of objects so I can run on the list a function from the object's class. I know that in python a list can basically contain many types of objects, is there a way to do it in python?

For example, I want ClientData's commands[] to be a list of CommandData objects:

class CommandData:
    command_type = -1
    command_identifier = 0  
    command = None
    status = "Pending"
    return_value = None


class ClientData():
    client_id = None  
    network = None  
    last_seen = None
    commands = []  # List of commandDatas that have been sent to the client
    waiting_commands = queue.Queue()  # Queue of commands waiting to go to the client

CodePudding user response:

If I am understanding your question correctly, you want your ClientData class to contain a list of instances of CommandData class, and that list will be called "commands", so that you can iterate through the "commands" list and perform some sort of function on each item?

If that is the case, then I think it would be just as simple as creating new instances of CommandData class and appending them to your desired list - there are no additional steps that should be required just because you are adding instances of a class as opposed to some other datatype.

CodePudding user response:

I don't really understand the question, but I think this would work:

class commandData:
  command_type = -1
  command_identifier = 0  
  command = None
  status = "Pending"
  return_value = None

class clientData:
  client_id = None  
  network = None  
  last_seen = None
  
  commands = [
    client_id,  
    network, 
    last_seen
  ]

  waiting_commands = queue.Queue()
  • Related