如何编写代码来循环指定的类

时间:2013-12-16 04:59:54

标签: python class

我正在编写一个代码,用于创建一个名为car的类。 在课堂上,我需要跟踪里程表,速度,驾驶员名称和赞助商。 我相信这个类本身的代码是正确的,但我试图创建20辆汽车参加比赛,但是当我尝试循环它时它只创建一个。我做错了什么。

这是我到目前为止的代码:

from random import randint

class car:
   odometer = 0
   speed = randint(1,120)
   driver = input("Drivers name:")
   sponsor = input("Car Sponsor:")
part_cars = 0
while (part_cars < int(20)):
   car
   part_cars += 1

1 个答案:

答案 0 :(得分:1)

car只是一个类,您需要初始化它。也许这段代码更好:

from random import randint

class Car:
    def __init__(self, odometer, speed, driver, sponsor):
        self.odometer = odometer
        self.speed = speed
        self.driver = driver
        self.sponsor = sponsor

cars = []
while len(cars) < 20:
    speed = randint(1, 120)
    driver = input("Drivers name:")
    sponsor = input("Car sponsor:")
    cars.append(Car(0, speed, driver, sponsor))

看一下tutorial可能会帮助你更好地理解课程。