Set attributes from dictionary in python

后端 未结 7 1688
南旧
南旧 2020-11-27 10:50

Is it possible to create an object from a dictionary in python in such a way that each key is an attribute of that object?

Something like this:

 d =          


        
7条回答
  •  忘掉有多难
    2020-11-27 11:03

    Setting attributes in this way is almost certainly not the best way to solve a problem. Either:

    1. You know what all the fields should be ahead of time. In that case, you can set all the attributes explicitly. This would look like

      class Employee(object):
          def __init__(self, name, last_name, age):
              self.name = name
              self.last_name = last_name
              self.age = age
      
      d = {'name': 'Oscar', 'last_name': 'Reyes', 'age':32 }
      e = Employee(**d) 
      
      print e.name # Oscar 
      print e.age + 10 # 42 
      

      or

    2. You don't know what all the fields should be ahead of time. In this case, you should store the data as a dict instead of polluting an objects namespace. Attributes are for static access. This case would look like

      class Employee(object):
          def __init__(self, data):
              self.data = data
      
      d = {'name': 'Oscar', 'last_name': 'Reyes', 'age':32 }
      e = Employee(d) 
      
      print e.data['name'] # Oscar 
      print e.data['age'] + 10 # 42 
      

    Another solution that is basically equivalent to case 1 is to use a collections.namedtuple. See van's answer for how to implement that.

提交回复
热议问题