classes vs dicts
Yermat
loic at fejoz.net
Fri May 7 03:47:38 EDT 2004
Larry Bates wrote:
> You will probably want a dictionary with keys to
> find people with classes stored to hold the information
> about the people. That way you can extend the class
> easily without disrupting your data structures.
>
> class person:
> def __init__(self, lastname, firstname, initial):
> self.lastname=lastname
> self.firstname=firstname
> self.initial=initial
> return
>
> #
> # Main Program
> #
> all_people={}
>
> all_people['LarryABates']=person('Larry','Bates','A')
> all_people['SomeOPerson']=person('Some','Person','O')
> [...]
Your all_people should also be a class then it can simplify stuff !
class PersonCollection:
def __init__(self):
self.all_people = {}
def add(self, person):
key = '%s%s%s' % (person.lastname,
person.initial,
person.firstname)
self.all_people[key] = person
def __getitem__(self, key):
return self.all_people[key]
then you will just do :
all_people = PersonCollection()
all_people.add(person('Larry','Bates','A'))
all_people.add(person('Some','Person','O'))
But you will still be able to do :
all_people['SomeOPerson'].phone = "+44 3 54 65 85 96"
If Objet-Oriented languages were invented, there was a reason !
--
Yermat
More information about the Python-list
mailing list