Defining And Accessing A List Of Custom Objects
Solution 1:
The most likely explanation is that you don't actually call [edit: now that you've edited the code in your question, we can eliminate this possibility]createPriceList()
before calling showPriceList()
.
Also, createPriceList()
has an error whereby you assign references to the same Car
object to all elements of the list. This error could also explain the behaviour, if and only if the last random()
function_giving_a_value()
call returns zero.
Finally, you're missing self.
in a couple of places [edit: again, you seem to have fixed some of these in a recent edit].
Here is how I would have written it:
import random
classCar:
def__init__(self, price):
self.price = price
classDay:
def__init__(self, n):
self.carList = []
for i inrange(n): # could also use list comprehension here
self.carList.append(Car(random.random()))
defprintPriceList(self):
for i, car inenumerate(self.carList):
print(i, car.price)
day = Day(20)
day.printPriceList()
Solution 2:
First of all, you're using the for loop in a 'wrong' way. You're creating an index from the length of a list, and then accesing elements from that same list using this index. This can be simplified, take for example your createPriceList method, it could look like this:
def createPriceList(self):
for car inself.carList
car.price = random()
print car.price
What you did in your example, is create one car before the loop, and changing it's value every time you store the car. That means that your carlist will be filled with references to the same car, so they will all have the same price.
The zeros are because random() returns a floating point number between 0 and 1. If this number is smaller then 0.1, the printed version will look like 0.0
Solution 3:
Depending on what you are trying to acheive, it might be better to keep single attributes for single Car()s, and build a list of Car() instances outside of the class:
import random
classCar:
def__init__(self):
self.price = random.random()
classDay:
def__init__(self):
self.cars = [Car() for each inrange(100)]
day = Day()
priceList = [car.price for car in day.cars]
The priceList should not exist within the class since it is redundant, in my opinion.
Post a Comment for "Defining And Accessing A List Of Custom Objects"