如何从字典中获取键/值对,并在类的实例中用作属性?我确定它应该通过一个 for 循环,但我不确定要使用什么语法。这是我的代码:
from random import randint
import time
drivers={}
class car:
def __init__(self, Driver, Sponsor, Odometer=0,Speed=randint(1,121)):
self.Driver = Driver
self.Sponsor = Sponsor
self.Odometer = Odometer
self.Speed = Speed
def update():
Odometer=Odometer+Speed*0.17
Speed = randint(1,121)
drivers['David']='Burger King'
drivers['Travis']='Dr Pepper'
drivers['Landon']='Precon Marine'
drivers['Jamie']='Cessna'
drivers['Juan']='Target'
drivers['Ken']='Federated Auto Parts'
drivers['Timmy']='OXYwater'
drivers['Josh']='MDS Transport'
drivers['Kurt']='Furniture Row'
drivers['Casey']='Geico'
drivers['Kasey']='Farmers Insurance'
drivers['Jeff']='Axalta'
drivers['Jimmie']='Lowes'
drivers['Dale']='National Guard'
drivers['Mike']='Plinker Tactical'
drivers['Denny']='FedEx'
drivers['Kyle']='Mars Brands'
drivers['Matt']='Husky'
drivers['Bobby']='Kingsford'
drivers['Clint']='5-Hour Energy'
我意识到驱动程序字典很长(并且可能有一种更简单的方法来添加所有这些驱动程序)。我需要在一个列表(或字典,在这种情况下)中添加 20 位车手和他们的赞助商。将它们简单地添加到类中而不是使用 for 循环会更容易吗?有没有办法添加司机姓名和赞助商作为属性,同时使用里程表和速度的默认值?