生成多个类并检索它们

时间:2016-11-28 16:41:42

标签: python python-3.x class

我想知道是否有"标准"如何动态生成类的多个实例并检索它们?

以下代码会产生10辆自行车,价格和颜色随机,我想知道如何给他们打电话?我玩了附加到列表,但返回的项目是字符串。

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'

1 个答案:

答案 0 :(得分:1)

每当你创建一个类(或任何类型的数据)时,都需要在某处引用它。如果不是,你可以认为它丢失了。

如果您需要创建一个类集合,那么集合可能是存储它们的好方法:

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)

根据您更新的问题,我认为问题在于您如何调用print_details。因为它是一个类成员,所以应该像这样调用它:

for i in bikes: 
    i.print_details()