On 01/21/2013 08:56 PM, 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

It'd work better if you actually instantiated Car, instead of just storing the class object multiple times.

Consider:
  usedCarLot[c] = Car(brandList[c], colorList[c], conditionList[c])


     usedCarLot[c].Brand = brandList[c]
     usedCarLot[c].Color = colorList[c]
     usedCarLot[c].Condition = conditionList[c]


Don't do those 3, since you already had to supply the values when constructing the object.


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


Next time, please supply the Python version, and state what you actually expected the output to represent.


--
DaveA
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to