如何通过字符串调用方法?

时间:2013-08-22 07:42:37

标签: python

我可以通过组合字符串来调用方法来处理数据吗?

例如,可以在代码中键入data.image.truecolor()吗?

data.image.truecolor() # This line is successful to call method

我的问题是:如果我有一个名为data的数据对象(不是字符串),如何将".image.truecolor" sting与call方法结合起来处理数据?

就像:

result=getattr(data,".image.truecolor")
result() # which is equivalent to the code above

当然,它失败了。我得到了AttributeError

因为有许多方法可以处理数据,例如:

data.image.fog()
data.image.ir108()
data.image.dnb()
data.image.overview()
# .... and other many methods

手动输入代码是愚蠢和丑陋的,不是吗?

由于这个原因,我希望我可以使用这段代码:

methods=["fog","ir108","dnb","overview"]
for method in methods:
    method=".image"+method
    result=getattr(data,method) # to call method to process the data
    result()  # to get the data processed

这样可以做到吗?

4 个答案:

答案 0 :(得分:10)

methods=["fog","ir108","dnb","overview"]
dataImage = data.image
for method in methods:
    result = getattr(dataImage ,method) # to call method to process the data
    result()  # to get the data processed

当你知道你将调用data.image的方法时,为什么不喜欢这样?否则,如果您不知道第二个属性image,则必须按照其他答案中的建议使用两个getattr级别。

答案 1 :(得分:5)

您需要两级getattr

im = getattr(data, 'image')
result=getattr(im, method)
result()

答案 2 :(得分:4)

您可以使用getattr按名称获取类实例方法,这是一个示例:

class A():
    def print_test(self):
        print "test"

a = A()
getattr(a, 'print_test')()  # prints 'test'

而且,在你的情况下,会有两个getattr个,一个用于图像,一个用于图像方法:

methods=["fog","ir108","dnb","overview"]
image = getattr(data, 'image')
for method in methods:
    result = getattr(image, method)
    result()

答案 3 :(得分:0)

您也可以使用eval("data.image.fog()")来调用/评估字符串中的表达式。

相关问题