What is the best way to store a list of properties one item at a time in Python?

I am creating a list of computers connected to the server. For each computer, I collect a list of properties. I am new to Python and programming and I find my solution rather clumsy.

I've done this with lists. I have a master list:, computer_list

and each computer is a different list with attributes like status, date, profile, etc.

computer_list = [cname1, cname2, cname3]
cname1 = ['online', '1/1/2012', 'desktop']

      

The disadvantages of this method become apparent the more I work and change this program. I hope for something more intuitive. I have searched for dictionaries but this solution seems almost as confusing as mine. The list in the list is functional, but not readable after the start of iteration and assignment. I'm sure there is a better way.

+3


source to share


2 answers


Make each computer an object:

class Computer(object):
    def __init__(self, name, status, date, kind):
        self.name   = name
        self.status = status
        self.date   = date
        self.kind   = kind

    @classmethod    # convenience method for not repeating the name
    def new_to_dict(cls, name, status, date, kind, dictionary):
        dictionary[name] = cls(name, status, date, kind)

      

Then save them in a dictionary or list.

computer_list = []
computer_list.append(Computer("rainier", "online", "1/1/2012", "desktop"))

computer_dict = {}
Computer.new_to_dict("baker", "online", "1/1/2012", "laptop", computer_dict)

      



Now, when you iterate over them, it's simple:

for comp in computer_list:
    print comp.name, comp.status, comp.date, comp.kind

      

You can also define __str__()

in the class to define how they are displayed, etc.

+2


source


Creating an object Computer

that stores fields that describe the properties and state of the computer is a viable approach.

You should read more about classes, but something like below should suit your needs:

class Computer(object):
    def __init__(self, status, date, name):
        self.status = status
        self.date = date
        self.hostname = name

    # (useful methods go here)

      



You may have initialized the objects Computer

and stored them in a list like this:

comp1 = Computer("online", "1/1/2012", "desktop")
comp2 = Computer("offline", "10/13/2012", "laptop")

computers = [comp1, comp2]

      

+4


source







All Articles