我有object1,它有很多子对象。这些子对象以object1.subobject
的形式访问。我有一个函数,它返回原始对象的子对象列表。我想做的就是遍历列表并访问每个子对象。像这样:
temp_list = listSubChildren(object1) #Get list of sub-objects
for sub_object in temp_list: #Iterate through list of sub-objects
blah = object1.sub-object #This is where I need help
#Do something with blah #So that I can access and use blah
我研究了一些类似的问题,人们使用dictionaries
和getattr
,但这两种方法都无法实现。你知道吗
将此添加到
object1
是其实例的类中:应该是这样的:
所以,getattr是你需要的。你知道吗
在我看来,如果您的} 函数。你知道吗
listSubChildren
方法像您暗示的那样返回字符串,那么您可以使用内置的^{或者举个例子:
最后一点可能是,根据您实际使用
blah
做什么,您可能还需要考虑operator.attrgetter
。考虑以下脚本:两个函数(
abc
,abc2
)的作用几乎相同。abc
返回列表[f.a, f.b, f.c]
而abc2
返回元组的速度要快得多,下面是我的结果前两行分别显示abc
和abc2
的输出,第三行和第四行显示操作需要多长时间:注意,在您的示例中,可以使用
getter = operator.attrgetter(*temp_list)
相关问题 更多 >
编程相关推荐