开发者

function name as as input of another function?

开发者 https://www.devze.com 2023-03-23 18:57 出处:网络
I an image processing enginner, and am using Python as a prototyping language. Most of the time, as I get thousands of images, named \"imagen.jpg\", n being the inc开发者_如何学Gorement.

I an image processing enginner, and am using Python as a prototyping language.

Most of the time, as I get thousands of images, named "imagen.jpg", n being the inc开发者_如何学Gorement.

So the main structure of my program may be seen as :

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

As you can see it, from one application to another, the only change would be the process_image function. Is there a way so that the process_image can be inserted as an input?

I would get a generic function, prototyped as : main_IP(imgRoot, stop_increment, process_image)

Thanks ! Julien


Functions can be passed around in python just like a string or any other object can.

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)


Yes, in python functions are first-class objects, so you can pass them as parameters just like any other data type.


Here is some code which demonstrates passing the name of the function you want to call, and also passing a reference to the function you want to call:

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)
0

精彩评论

暂无评论...
验证码 换一张
取 消