Set attributes from dictionary in python

后端 未结 7 1629
南旧
南旧 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:21

    similar to using a dict, you could just use kwargs like so:

    class Person:
       def __init__(self, **kwargs):
           self.properties = kwargs
    
       def get_property(self, key):
           return self.properties.get(key, None)
    
       def main():
           timmy = Person(color = 'red')
           print(timmy.get_property('color')) #prints 'red'
    
    0 讨论(0)
提交回复
热议问题