假设我有对象具有键“dlist0”和属性“row_id”我可以访问为
getattr(dlist0,'row_id')
然后返回值 但如果我有一本字典
ddict0 = {'row_id':4, 'name':'account_balance'}
getattr(ddict0,'row_id')
这是行不通的
我的问题是如何以相同的方式访问 ddict0 和 dlist0
谁能帮帮我?
最佳答案
字典有项目,因此使用定义为 __getitem__()
的任何内容来检索键的值。
对象具有属性,因此使用 __getattr__()
来检索属性的值。
如果需要,理论上您可以覆盖一个指向另一个 - 但为什么需要这样做?为什么不直接编写辅助函数:
python 2.x:
def get_value(some_thing, some_key):
if type(some_thing) in ('dict','tuple','list'):
return some_thing[some_key]
else:
return getattr(some_thing, some_key)
Python 3.x:
def get_value(some_thing, some_key):
if type(some_thing) in (dict,tuple,list):
return some_thing[some_key]
else:
return getattr(some_thing, some_key)
关于python字典键与对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3279011/