我在 StackOverflow 中找不到相关问题,所以...
我有一本字典,其中包含以下形式的行星和恒星数据:
dict = {'name': value, 'mass' : value, 'radius': value, etc..}
该字典的键与我为其赋值的 Planet 和 Star 类的属性具有相同的名称。
我想做的是在根据其他填充字段计算某些缺失的数据字段后,计算所有填充的恒星和行星对象的缺失信息量...
有什么方法可以逐步遍历该字典的键并使用该键保存的字符串引用 Star/Planet 对象的属性吗?
所以类似:
for planetObjs in planets:
for key in dict.iterkeys():
if planetObj.key == None:
countMissingDict[key] += 1
我如何引用 key 所保存的字符串,该字符串与用作 Planet 对象中的属性的字符串相同?这可能吗?
最佳答案
使用getattr
:
getattr(object, name[, default]) -> value
Get a named attribute from an object;
getattr(x, 'y')
is equivalent tox.y
. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case
您可以将代码缩短为:
from collections import Counter
countMissingDict = Counter(key for planetObjs in planets for key in dic
if getattr(planetObjs, key) is None)
注意:不要使用dict
作为变量名。
关于python - 可以使用字符串来引用对象属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19458996/