gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:04:13 24 4
gpt4 key购买 nike

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

比如在代码中输入data.image.truecolor()就可以了?

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

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

就像:

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

这样可以吗?

最佳答案

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

关于python - 如何通过字符串调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18374447/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com