我有一个像这样的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
。
答案 0 :(得分:3)
您正在寻找setattr()
:
def __init__(self, details):
for field,value in details.iteritems():
setattr(self, field, value)
答案 1 :(得分: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')
答案 2 :(得分:0)