2011-11-01 102 views
0

我有一個Python類這樣分配值一類動態

class Car(Base): 

    def __init__(self, details): 
     for field,value in details.iteritems(): 
      self[field] = value 

,我這樣稱呼它

car_details['make'] = 'Dodge' 
car_details['model'] = 'Ram' 

car = Car(car_details) 

但是它失敗

TypeError: 'Car' object does not support item assignment 

我想設置它,所以一旦類已經初始化,我就可以使用car.make

+1

標題misleadi NG。你正試圖使用​​一個類實例作爲字典。 – delnan

回答

3

你正在尋找setattr()

def __init__(self, details): 
    for field,value in details.iteritems(): 
     setattr(self, field, value) 
2

你可以使用Alex Martelli's Bunch

class Car(Base):  
    def __init__(self, details): 
     self.__dict__.update(details) 

請注意,如果你改變了__init__調用簽名def __init__(self, **details)

class Car(Base):  
    def __init__(self, **details): 
     super(Car,self).__init__(**details) 

那麼你可以做的Car初始化更容易:

car=Car(make='Dodge',model='Ram')