我一直在寻找这个问题,并且还看过以前问过的问题:
如何在python中动态创建类的实例?
python是否具有Java Class.forName()的等价物?
你能用字符串在python中实例化一个类吗?
还有更多,在其中一些,他们正在导入类或在定义中以某种方式使用类的名称。
编辑:
我需要将列表作为输入,并创建列表中包含字符串的类作为其名称。
store_list = {'store1', 'storeabc', 'store234'}现在我能做到,
store1 = type(store_list[0], (models.Model,), attrs) storeabc = type(store_list[1], (models.Model,), attrs) store234 = type(store_list[2], (models.Model), attrs)但是我仍然必须在代码中以某种方式使用类的名称,我无法知道列表将是什么,并且我希望使用列表中的名称创建类。
I have been looking for this for quite sometime and also looked at previously asked questions like:
how to dynamically create an instance of a class in python?
Does python have an equivalent to Java Class.forName()?
Can you use a string to instantiate a class in python?
And also many more, in some of them they are importing the class or using the name of the class somehow in definition.
Edit:
I need to take a list as input and create classes with strings in the list as their name.
store_list = {'store1', 'storeabc', 'store234'}Now i can do,
store1 = type(store_list[0], (models.Model,), attrs) storeabc = type(store_list[1], (models.Model,), attrs) store234 = type(store_list[2], (models.Model), attrs)But i still have to use the names of the class in some way in the code, i have no way of knowing what the list will be, and i want the classes to be created with name taken from the list.
最满意答案
您可以将动态创建的类存储到字典中,将类名映射到类。 这样,您可以使用这样的字典在代码中稍后按名称访问类,例如创建实例。 例如:
store_list = {'store1', 'storeabc', 'store234'} name2class = {} for name in store_list: name2class[name] = type(name, (models.Model,), attrs) . . . my_instance = name2class[name](...)You could store the classes you're dynamically creating into a dictionary, mapping class names to classes. This way you can use such a dictionary to access your classes by name later in your code, e.g. to create instances. For example:
store_list = {'store1', 'storeabc', 'store234'} name2class = {} for name in store_list: name2class[name] = type(name, (models.Model,), attrs) . . . my_instance = name2class[name](...)更多推荐
发布评论