如何從字典中獲取鍵/值對,並在類中的實例中使用屬性?我確定它應該通過for循環,但我不確定使用什麼語法。這裏是我的代碼:作業:Python 3.3:將字典中的鍵和值添加到類
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循環會更容易嗎?有沒有辦法將駕駛員姓名和贊助商添加爲屬性,同時使用里程錶和速度的默認值?
作爲一個側面說明,你真的應該與你的大寫一致。理想情況下遵循[PEP 8](http://www.python.org/dev/peps/pep-0008/)style:'Car','drivers','self.driver'等。但即使您選擇使用不同的風格,使用你一貫選擇的任何東西。 – abarnert 2013-04-29 20:50:49