动态地为类分配值

时间:2011-11-01 11:56:05

标签: python variable-assignment

我有一个像这样的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

3 个答案:

答案 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)