Newbie class instance tracking system
Lyle Johnson
ljohnson at resgen.com
Wed May 9 17:42:33 EDT 2001
> I am new to Python and I am having trouble with the following code. In
short,
> Why doesn't it work? I thought that variable names "spring into
existence" in
> a similar fasion to perl...
Although Python's error message wasn't very helpful in this case, the
problem was that for a new key (or car company name) in the dictionary, you
didn't specify the data type (which in your case should be a list). I've
modified your code (shown below) to initialize the dictionary entry to an
empty list if it encounters a new key; the relevant lines are:
if not Maker.all_cars.has_key(carCompany):
Maker.all_cars[carCompany] = []
Hope this helps,
Lyle
class Maker:
all_cars={}
def __init__(self,carName=None,carCompany=None):
self.carName = carName
self.carCompany = carCompany
if not Maker.all_cars.has_key(carCompany):
Maker.all_cars[carCompany] = []
Maker.all_cars[carCompany].append(carName)
prelude = Maker(carName='prelude',carCompany='Honda')
accord = Maker(carName='accord',carCompany='Honda')
for carCompany in Maker.all_cars.keys():
print "Cars from %s:" % carCompany
for carName in Maker.all_cars[carCompany]:
print " %s" % carName
More information about the Python-list
mailing list