[英]For loop with object's attributes in Python
I am working with objects in Python and all I wanted was to replace the attribute in a for loop to get the data out of the object. 我正在使用Python处理对象,而我想要做的就是替换for循环中的属性以从对象中获取数据。 Here is my code:
这是我的代码:
def calculate_something(dictionaryWithObjects):
for attribute in ['attr1', 'attr2', 'attr3']:
dataA1, dataA2 = dictionaryWithObjects['Object1'].attribute
dataB1, dataB2 = dictionaryWithObjects['Object2'].attribute
dataC1, dataC2 = dictionaryWithObjects['Object3'].attribute
So this is more or less what I think I need. 因此,这或多或少是我认为我需要的。 I will use the data for calculations afterwards.
之后,我将使用这些数据进行计算。 But it gives an error saying that the object has no attribute called ".attribute".
但是它给出一个错误,指出该对象没有名为“ .attribute”的属性。 Of course it doesn't, I meant it to replace the 'attr1' in there.
当然不是,我的意思是替换那里的“ attr1”。
What am I doing wrong? 我究竟做错了什么?
为了按名称访问实例属性,应使用[Python]: getattr ( object,name [,default] ) ,例如:
dataA1, dataA2 = getattr(dictionaryWithObjects['Object1'], attribute)
Try something like this: 尝试这样的事情:
def calculate_something(dictionaryWithObjects):
for attribute in ['attr1', 'attr2', 'attr3']:
dataA1, dataA2 = dictionaryWithObjects['Object1'][attribute]
您可以使用eval
:
data=eval('Object1.'+attribute)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.