JONAS402 JONAS402 - 8 days ago 6
Python Question

Spawn multiple classes and retrieve them

I'm wondering if there is a "standard" way to spawn multiple instances of a class dynamically and retrieve them?

The below code spawns 10 bikes, with random prices and colours, I'm wondering how I would call them back? I played around with appending to a list but the returned items are strings.

bikes = []

class Bike:

style = ""
price = 0
colour = ""

def __init__(self, style, price, colour):
self.style = style
self.price = price
self.colour = colour
self.description = "a {0} {2} worth £{1}".format(self.colour, self.price, self.style)

def print_details(self):
print("description: {0}".format(self.description))

for b in range(10):
price = random.choice(random_prices)
colour = random.choice(random_colours)
bike = "bike" + str(b)
bike = Bike('bike', price, colour)
bikes.append(bike)

for i in bikes:
print_details(i)


Traceback (most recent call last):
print("description: {0}".format(self.description))
AttributeError: 'str' object has no attribute 'description'

Answer

Any time you create a class (or any kind of data) it would need to be referenced somewhere. If it isn't, you can consider it lost.

If you need to create a collection of classes, then a collection is probably a good way to store them:

bikes = []
for b in range(10):
    price = random.choice(random_prices)
    colour = random.choice(random_colours)
    bike = "bike" + str(b)
    bike = Bike('bike', price, colour) 
    bikes.append(bike)

Based on your updated question, I believe the issue is in how you're calling print_details. Because it's a class member, it should be called like this:

for i in bikes: 
    i.print_details()