我想做这样的事情:
from dotDict import dotdictify
life = {'bigBang':
{'stars':
{'planets': []}
}
}
dotdictify(life)
# This would be the regular way:
life['bigBang']['stars']['planets'] = {'earth': {'singleCellLife': {}}}
# But how can we make this work?
life.bigBang.stars.planets.earth = {'singleCellLife': {}}
#Also creating new child objects if none exist, using the following syntax:
life.bigBang.stars.planets.earth.multiCellLife = {'reptiles':{},'mammals':{}}
我的动机是提高代码的简洁性,如果可能的话,使用类似于Javascript的语法来访问JSON对象以实现高效的跨平台开发。(我也使用Py2JS和类似的工具。)
下面是另一个解决方案:
然后在python控制台中:
打印正确的值
以下是创造这种体验的一种方法:
下面是嵌套属性字典的另一个实现(灵感来源于Curt Hagenlocher的回答,分解到本质):
这在Python2和3中都有效:
Python3需要在
__getattr__
中将KeyError转换为AttributeError,这样hasattr
也可以在找不到属性的情况下工作:相关问题 更多 >
编程相关推荐