简体   繁体   中英

calling a function from a list in python

Take this example:

presets = [
    "eggs",
    "bacon"
    ]

print(presets[0])
>>> eggs

Why can a not do the same thing, with a list of items to execute? Take this example:

from animations import animation_2, animation_3, animation_4
presets = [
    animation_2.iterate(animations_templates_path, thumbnails_final),
    animation_3.iterate(animations_templates_path, thumbnails_final),
    animation_4.iterate(animations_templates_path, thumbnails_final)
    ]

When I run this (both WITH and WITHOUT the preset[n] ) it executes all three commands in the list. Why is this? I would like to have a list of those presets, and call them via am index number. What am I doing wrong?

It executes the items because that's what you are telling it to do. Your code is exactly the same as this:

p1 = animation_2.iterate(animations_templates_path, thumbnails_final)
p2 = animation_3.iterate(animations_templates_path, thumbnails_final)
p3 = animation_4.iterate(animations_templates_path, thumbnails_final)
presets = [p1, p2, p3]

Python has no way of knowing that you didn't intend to call those functions.

One solution is to store a tuple:

presets = [
    (animation_2.iterate, animations_templates_path, thumbnails_final),
    (animation_3.iterate, animations_templates_path, thumbnails_final),
    (animation_4.iterate(animations_templates_path, thumbnails_final),

]

That stores the function and the arguments without calling the function. You can iterate over the list at a later date and execute the function.

You can store the actual function objects in a list

from animations import animation_1, animation_2, animation_3
presets = [
    animation_2.iterate,
    animation_3.iterate,
    animation_4.iterate
    ]

Then call the desired function based on its index. This way the function is not executed upon constructing the list , rather it is only executed once you call it.

presets[0](animations_templates_path, thumbnails_final)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM