我发现访问dict密钥更加方便,obj.foo而不是obj['foo'],所以我写了这个代码片段:
class AttributeDict(dict):
def __getattr__(self, attr):
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value
Run Code Online (Sandbox Code Playgroud)
但是,我认为必须有一些原因,Python不提供开箱即用的功能.以这种方式访问dict密钥有什么警告和陷阱?
我希望能够做到这样的事情:
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':{}}
Run Code Online (Sandbox Code Playgroud)
我的动机是改进代码的简洁性,如果可能的话,使用与Javascript类似的语法来访问JSON对象,以实现高效的跨平台开发.(我也使用Py2JS和类似的.)
说我有在Python几个变量或对象a,b,c,...
如何轻松地将这些变量转储到Python中的命名空间中并在以后恢复它们?(例如,以相同的方式argparse将各种变量包装到命名空间中).
以下是我希望如何在命名空间之间转储内容的两个示例:
function (bar):
# We start with a, b and c
a = 10
b = 20
c = "hello world"
# We can dump anything we want into e, by just passing things as arguments:
e = dump_into_namespace(a, b, c)
del a, b, c
print (e.a + e.b) # Prints 30
return e # We can return e if we want. This is just …Run Code Online (Sandbox Code Playgroud)