首页 > 解决方案 > Accessing a dictionary as attributes of a custom class

问题描述

This is easier to explain with an example. Imagine I have the following dictionary..

myapps = {'app_1': {'username': 'admin',
                    'pwd': 'S3cret',
                    'ports': [8080, 443],
                    'users': {'user1': 'john',
                              'user2': 'ruth'}},
          'app_2': {'username': 'user1', 
                    'pwd': 'P@ssword'}
}

Now I'd like to use the data of this dictionary in the following manner:

print("App_2 username = ", myapps.app_2.username) # prints App_2 username = user1
print("App_2 pwd = ",      myapps.app_2.pwd)      # prints App_2 pwd = P@ssword
print("App_1 ports = ",    myapps.app_1.ports)    # prints App_1 ports = [8080, 443]

myapps.app_2.username = "MyNewAdminAccount"
print("App_2 username = ", myapps.app_2.username) # prints App_2 username = MyNewAdminAccount

I'm basically trying to write a class that can take a dictionary, go through it recursively and generate attributes for each key and subkey given in my dictionary.

标签: python

解决方案


If I understand your question correctly, you are looking for a DotDict: Recursive DotDict

With this class you can remap the __getattr__ and _setattr__, which are called on the dot-operator to use the __getitem__ and __setitem__ functions which access dictionary data.


推荐阅读