使用变量作为变量的一部分

2024-10-06 07:36:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有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

我研究了一些类似的问题,人们使用dictionariesgetattr,但这两种方法都无法实现。你知道吗


Tags: of对象函数列表forgetobjectsobject
3条回答

将此添加到object1是其实例的类中:

def getSubObjectAttributes(self):
    childAttrNames = "first second third".split()
    return [getattr(self, attrname, None) for attrname in childAttrNames]

应该是这样的:

temp_list = [] 
for property_name in needed_property_names:
    temp_list.append(getattr(object1, property_name))

所以,getattr是你需要的。你知道吗

在我看来,如果您的listSubChildren方法像您暗示的那样返回字符串,那么您可以使用内置的^{}函数。你知道吗

>>> class foo: pass
... 
>>> a = foo()
>>> a.bar = 1
>>> getattr(a,'bar')
1
>>> getattr(a,'baz',"Oops, foo doesn't have an attrbute baz")
"Oops, foo doesn't have an attrbute baz"

或者举个例子:

for name in temp_list:
    blah = getattr(object1,name)

最后一点可能是,根据您实际使用blah做什么,您可能还需要考虑operator.attrgetter。考虑以下脚本:

import timeit
import operator

class foo(object):
    def __init__(self):
        self.a = 1
        self.b = 2
        self.c = 3

def abc(f):
    return [getattr(f,x) for x in ('a','b','c')]

abc2 = operator.attrgetter('a','b','c')

f = foo()
print abc(f)
print abc2(f)

print timeit.timeit('abc(f)','from __main__ import abc,f')
print timeit.timeit('abc2(f)','from __main__ import abc2,f')

两个函数(abcabc2)的作用几乎相同。abc返回列表[f.a, f.b, f.c]abc2返回元组的速度要快得多,下面是我的结果前两行分别显示abcabc2的输出,第三行和第四行显示操作需要多长时间:

[1, 2, 3]
(1, 2, 3)
0.781795024872
0.247200965881

注意,在您的示例中,可以使用getter = operator.attrgetter(*temp_list)

相关问题 更多 >