是否可以通过python中的字典创建对象,使得每个键都是该对象的属性?
像这样:
d = { 'name': 'Oscar', 'lastName': 'Reyes', 'age':32 } e = Employee(d) print e.name # Oscar print e.age + 10 # 42
当然,是这样的:
class Employee(object): def __init__(self, initial_data): for key in initial_data: setattr(self, key, initial_data[key])
更新资料
正如布伦特·纳什(Brent Nash)所建议的那样,您还可以通过允许使用关键字参数来使其更加灵活:
class Employee(object): def __init__(self, *initial_data, **kwargs): for dictionary in initial_data: for key in dictionary: setattr(self, key, dictionary[key]) for key in kwargs: setattr(self, key, kwargs[key])
然后您可以这样称呼它:
e = Employee({"name": "abc", "age": 32})
或像这样:
e = Employee(name="abc", age=32)
甚至像这样:
employee_template = {"role": "minion"} e = Employee(employee_template, name="abc", age=32)