我是python类的新手,正在寻找可以解释为什么我遇到此问题的人。
我上了这个课:
class TrackingMeasure:
Touches = 'Possessions'
DefensiveImpact = 'Defense'
当我尝试运行此循环时:
tracking_refs = ['Touches','DefensiveImpact']
for x in tracking_refs:
print(TrackingMeasure.x)
我收到此错误:
AttributeError: type object 'TrackingMeasure' has no attribute 'x'
我敢肯定,这对别人来说很容易解释,因此,我们将不胜感激。
答案 0 :(得分:1)
您需要使用该类的内部字典来做到这一点:
print(TrackingMeasure.__dict__[x])
答案 1 :(得分:1)
您可以使用getattr
:
tracking_refs = ['Touches','DefensiveImpact']
for x in tracking_refs:
print(getattr(TrackingMeasure, x))
答案 2 :(得分:1)
getattr(对象,字符串)
this_tm = TrackingMeasure
for x in tracking_refs:
print(getattr(this_tm,x))