如何在python中动态创建类的实例? [英] how to dynamically create an instance of a class in python?

查看:48
本文介绍了如何在python中动态创建类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类名列表,想动态创建它们的实例.例如:

I have list of class names and want to create their instances dynamically. for example:

names=[
'foo.baa.a',
'foo.daa.c',
'foo.AA',
 ....
]

def save(cName, argument):
 aa = create_instance(cName) # how to do it?
 aa.save(argument)

save(random_from(names), arg)

如何在 Python 中动态创建该实例?谢谢!

How to dynamically create that instances in Python? thanks!

推荐答案

这通常称为反思,有时也称为自省.查看一个类似的问题,这些问题对您正在尝试做的事情有答案:

This is often referred to as reflection or sometimes introspection. Check out a similar questions that have an answer for what you are trying to do:

Python 是否有等效于 Java 的类 forname

你可以使用字符串来实例化吗Python 中的类

这篇关于如何在python中动态创建类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆