函数名作为另一个函数的输入?

2024-05-18 06:53:21 发布

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

我是一个图像处理工程师,使用Python作为原型语言。在

大多数时候,当我看到上千张照片时图像.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函数。 是否有方法可以将进程图像作为输入插入?在

我会得到一个通用函数,原型为: 主IP(imgRoot、停止增量、进程映像)

谢谢! 朱利安


Tags: the函数name图像imageip应用程序img
3条回答

是的,在python中函数是一级对象,因此可以像其他任何数据类型一样将它们作为参数传递。在

函数可以像字符串或任何其他对象一样在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)

下面是一些代码,演示如何传递要调用的函数的名称,以及传递对要调用的函数的引用:

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)

相关问题 更多 >