python - 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.
解决方案
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.
推荐阅读
- gulp - 如何在本地运行(来自 Ghost 的 Casper 主题)开发服务器?
- android - 协程挂起函数和阻塞调用
- laravel - 状态 [42000]:语法错误或访问冲突:1066 不是唯一的表/别名
- jquery - html输入的数学添加问题
- python - 我可以在 One Class SVM 中设置污染值吗?
- c# - 如何在 Unity 播放器或内置游戏中使用 Roslyn 编译器处理可能包含 lambda 表达式的表达式?
- typescript - 禁止强制转换为原始
- python - 从python的DataFramein单元格中删除重复值
- highcharts - 带有 highcharts.css 导入的 Highcharts styledMode 导致饼图图例悬停应用于所有图例项
- c - 以可爱的方式打印一棵树(C)