>>> from __future__ import print_function
>>> import json
>>> from types import SimpleNamespace as Namespace
>>> data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'
>>> x = json.loads(data, object_hook=lambda d: Namespace(**d))
>>> x.name
'John Smith'
但是,如果“名称”来自变量,我该如何访问它?
>>> foo='name'
>>> x.foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'types.SimpleNamespace' object has no attribute 'foo'
>>>
答案 0 :(得分:1)
使用getattr
函数:
getattr(x, foo)
当x.name
时将用作foo = 'name'
。