簡體   English   中英

從python中的列表調用函數

[英]calling a function from a list in python

舉個例子:

presets = [
    "eggs",
    "bacon"
    ]

print(presets[0])
>>> eggs

為什么不能用要執行的項目列表來做同樣的事情? 舉個例子:

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

當我運行此命令時(WITH和WITHOUT不帶preset[n] ),它將執行列表中的所有三個命令。 為什么是這樣? 我想列出這些預設,並通過索引號調用它們。 我究竟做錯了什么?

它執行項目,因為這就是您要執行的操作。 您的代碼與此完全相同:

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無法知道您不打算調用這些函數。

一種解決方案是存儲元組:

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

]

該函數存儲函數和參數,而無需調用函數。 您可以在以后迭代列表並執行該功能。

您可以將實際功能對象存儲在列表中

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

然后根據其索引調用所需的函數。 這樣,函數不會在構造list執行,而是僅在調用它后才執行。

presets[0](animations_templates_path, thumbnails_final)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM