我正在尝试使用'while'循环来检查类中属性的条件。具体来说,我需要检查里程表以查看是否有任何物体达到500.该代码用于模拟比赛。所以它需要检查整个类,看看任何物体的里程表是否达到500(或超过),当发生这种情况时,停止添加到里程表,并宣布获胜者。但是现在,'while'循环运行直到每个物体里程表达到500.将'while'循环移动到'for'循环之前会导致错误,说汽车类没有里程表属性... < / p>
所以我的问题是,如何让我的'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)
答案 0 :(得分: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)