On 2013-01-22 01:56, Brian D wrote:
Hi,
I'm trying to instantiate a class object repeated times, dynamically for as
many times as are required, storing each class object in a container to later
write out to a database. It kind of looks like what's needed is a
two-dimensional class object, but I can't quite conceptualize how to do that.
A simpler approach might be to just store class objects in a dictionary, using
a reference value (or table row number/ID) as the key.
In the real-world application, I'm parsing row, column values out of a table in
a document which will have not more than about 20 rows, but I can't expect the
document output to leave columns well-ordered. I want to be able to call the
class objects by their respective row number.
A starter example follows, but it's clear that only the last instance of the
class is stored.
I'm not quite finding what I want from online searches, so what recommendations
might Python users make for the best way to do this?
Maybe I need to re-think the approach?
Thanks,
Brian
class Car(object):
def __init__(self, Brand, Color, Condition):
self.Brand = Brand
self.Color = Color
self.Condition = Condition
brandList = ['Ford', 'Toyota', 'Fiat']
colorList = ['Red', 'Green', 'Yellow']
conditionList = ['Excellent', 'Good', 'Needs Help']
usedCarLot = {}
for c in range(0, len(brandList)):
print c, brandList[c]
usedCarLot[c] = Car
usedCarLot[c].Brand = brandList[c]
usedCarLot[c].Color = colorList[c]
usedCarLot[c].Condition = conditionList[c]
for k, v in usedCarLot.items():
print k, v.Brand, v.Color, v.Condition
0 Ford
1 Toyota
2 Fiat
0 Fiat Yellow Needs Help
1 Fiat Yellow Needs Help
2 Fiat Yellow Needs Help
You're repeatedly putting the class itself in the dict and setting its
(the class's) attributes; you're not even using the __init__ method you
defined.
What you should be doing is creating instances of the class:
for c in range(len(brandList)):
print c, brandList[c]
usedCarLot[c] = Car(brandList[c], colorList[c], conditionList[c])
--
http://mail.python.org/mailman/listinfo/python-list