使用字符串作为类名在python中创建一个类(Creating a class in python using a string as the class name)

编程入门 行业动态 更新时间:2024-10-28 11:25:25
使用字符串作为类名在python中创建一个类(Creating a class in python using a string as the class name)

我一直在寻找这个问题,并且还看过以前问过的问题:

如何在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](...)

更多推荐

本文发布于:2023-08-06 22:28:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1457682.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   创建一个   python   string   Creating

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!