函数名作为另一个函数的输入?
我是一名图像处理工程师,正在使用Python作为原型开发语言。
大多数时候,我会处理成千上万的图像,这些图像的命名方式是“imagen.jpg”,其中n是一个递增的数字。
所以我程序的主要结构可以看作是:
def main_IP(imgRoot, stop_ncrement):
name = update_the_increment(imgRoot, stop_increment)
img = load_the_image(name)
out_img = process_image(img)
displays_images(img, out_img)
return out_img
正如你所看到的,从一个应用程序到另一个应用程序,唯一的变化就是process_image这个函数。
有没有办法让process_image函数可以作为输入呢?
我想得到一个通用的函数,原型是:
main_IP(imgRoot, stop_increment, process_image)
谢谢!
朱利安
3 个回答
1
这里有一段代码,演示了如何传递你想要调用的函数的名字,以及如何传递你想要调用的函数的引用:
def A():
return "A!"
def B():
return "B!"
def CallByName(funcName):
return globals()[funcName]()
def CallByReference(func):
return func()
print CallByName("A")
functionB = B
print CallByReference(functionB)
2
没错,在Python中,函数被视为一种重要的对象,所以你可以像处理其他数据类型一样,把函数当作参数传递。
8
在Python中,函数可以像字符串或其他任何对象一样被传递。
def processImage(...):
pass
def main_IP(imgRoot, stop_ncrement, process_image):
name = update_the_increment(imgRoot, stop_increment)
img = load_the_image(name)
out_img = process_image(img)
displays_images(img, out_img)
return out_img
main_IP('./', 100, processImage)