Python替换for循环中的表达式

2024-03-28 20:31:54 发布

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

我的函数myfunction需要自定义类作为输入。我定义了很多自定义类。我想用自定义类的每个定义调用myfunction。 有什么简单的方法吗

基本上我想这样做:

from custom_lib import Class_0,Class_1,....Class_100

for i in range(101):
    myfunction(Class_i)

并替换for循环中的i,以便用所有类调用函数。 提前谢谢


Tags: 方法函数infromimportfor定义lib
2条回答
import custom_lib
for cl in dir(custom_lib):
    if cl.startswith('Class_'):
        myfunction(getattr(custom_lib, cl))

创建所有类的list,并在for中使用它:

class_list = [Class_0,Class_1,....Class_100] # Write the classes instead of ....
for cl in class_list:
    myfunction(cl)

相关问题 更多 >