Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用for循环实例化类列表?_Python_Python 3.x_Class - Fatal编程技术网

Python 如何使用for循环实例化类列表?

Python 如何使用for循环实例化类列表?,python,python-3.x,class,Python,Python 3.x,Class,如何从不同的类列表中实例化对象,每个类在不同的模块中定义?比如: a.py: class a(): def __init__(): print('a called') class b(): def __init__(): print('b called') b.py: class a(): def __init__(): print('a called') class b(): def __init__():

如何从不同的类列表中实例化对象,每个类在不同的模块中定义?比如:

a.py

class a():
    def __init__():
        print('a called')
class b():
    def __init__():
        print('b called')
b.py

class a():
    def __init__():
        print('a called')
class b():
    def __init__():
        print('b called')
main.py

import a
import b

classes = ['a', 'b']

for class in classes:
    class = class()

类是否需要由字符串列表引用?你可以做:

classes = [a.a, b.b]
for cls in classes:
    class_instance = cls()

假设您在编写程序时知道所有类(即,您不尝试在运行时动态发现它们),您可以将创建内容放入列表文字中:

from a import a
from b import b

objects = [a(), b()]
如果你从某个地方得到一些类的列表,那么只需循环该列表并调用每个类即可

import a
import b

classes = [a.a, b.b]
objects = [cls() for cls in classes]

在用户输入类名的情况下,您需要处理字符串,就像在最初的示例中,在字符串列表中定义类名一样。在本例中,使用
eval(classname)
获取类的构造函数/init

from a import a
from b import b
classnames = ["a", "b"]
instances = [eval(n)() for n in classnames]
PS:您在init-定义中忘记了self,这会导致错误uccurs:
\uuuuuuu init\uuuuuuuuuuuu()接受0个位置参数,但给出了1个