简体   繁体   English

从python中的列表调用函数

[英]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. 当我运行此命令时(WITH和WITHOUT不带preset[n] ),它将执行列表中的所有三个命令。 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. Python无法知道您不打算调用这些函数。

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. 这样,函数不会在构造list执行,而是仅在调用它后才执行。

presets[0](animations_templates_path, thumbnails_final)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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