0

我正在尝试使用“while”循环来检查类中属性的条件。具体来说,我需要检查里程表以查看是否有任何物体达到 500。代码用于模拟比赛。所以它需要检查类作为一个整体,看看任何对象的里程表是否达到500(或以上),当发生这种情况时,停止添加到里程表,并宣布获胜者。但是,现在,“while”循环一直运行,直到每个对象的里程表达到 500。将“while”循环移动到“for”循环之前会导致错误,说汽车类没有里程表属性......

所以我的问题是,如何让我的“while”循环为整个班级工作,而不是分别为每个对象工作?还是我试图完全错误地解决这个问题?我在这里不知所措,但我认为我正确地解决了这个问题。这是我所拥有的,完整的。

from random import randint
import time
class car:
    def __init__(self, Driver, Sponsor, Odometer=0, Speed=0):
        self.Driver = Driver
        self.Sponsor = Sponsor
        self.Odometer = Odometer
        self.Speed = randint(1,121)
drivers={'David': 'Burger King',
         'Travis': 'Dr Pepper',
         'Landon': 'Precon Marine',
         'Jamie': 'Cessna',
         'Juan': 'Target',
         'Ken': 'Federated Auto Parts',
         'Timmy': 'OXYwater',
         'Josh': 'MDS Transport',
         'Kurt': 'Furniture Row',
         'Casey': 'Geico',
         'Kasey': 'Farmers Insurance',
         'Jeff': 'Axalta',
         'Jimmie': 'Lowes',
         'Dale': 'National Guard',
         'Mike': 'Plinker Tactical',
         'Denny': 'FedEx',
         'Kyle': 'Mars Brands',
         'Matt': 'Husky',
         'Bobby': 'Kingsford',
         'Clint': '5-Hour Energy'
}
cars = [car(driver, sponsor) for driver, sponsor in drivers.items()]
for car in cars:
    while car.Odometer < 500:
        car.Odometer=car.Odometer+car.Speed*0.17
        car.Speed = randint(1,121)
        print(car.Driver, car.Odometer, car.Speed)
4

1 回答 1

1

也许是这样的?

from operator import attrgetter

cars = [car(driver, sponsor) for driver, sponsor in drivers.items()]

# we find the car with the max Odometer
car_max_odometer = max(cars, key=attrgetter("Odometer"))
while car_max_odometer.Odometer < 500
    for car in cars:
        car.Odometer=car.Odometer+car.Speed*0.17
        car.Speed = randint(1,121)
        print(car.Driver, car.Odometer, car.Speed)
    car_max_odometer = max(cars, key=attrgetter("Odometer"))
print("We have a winner! {}, {}, {}".format(car_max_odometer.Driver, car_max_odometer.Odometer, car_max_odometer.Speed))

您还应该查看 PEP8,您的类名、变量名和空格不遵循约定。

此外:

self.Speed = randint(1,121)

应该:

self.Speed = Speed

由于您将速度作为关键字参数传递

如果你希望它在速度为 0 时默认为 randint(1,121) 或者如果它是 None 那么你可以这样做

self.Speed = Speed or randint(1,121)
于 2013-04-30T01:47:12.163 回答