使每台计算机成为对象:
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)
然后将它们存储在字典或列表中。
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)
现在,当您遍历它们时,它很简单:
for comp in computer_list:
print comp.name, comp.status, comp.date, comp.kind
您还可以__str__()
在类上定义以定义它们的显示方式,等等。