使用类的名称实例化类的对象

2024-04-26 14:58:22 发布

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

我想写一个python实用程序,给定一个类名作为输入(可能是一个字符串),加上可以找到类的模块名,以及该类的构造函数的参数,它实例化此类的对象。你知道吗

在python中可以这样做吗?如果是,最好的选择是什么?你知道吗


Tags: 模块对象实例字符串实用程序参数类名
1条回答
网友
1楼 · 发布于 2024-04-26 14:58:22

可以使用^{} function访问模块中的任何名称;使用该名称检索对所需类对象的引用:

klass = getattr(module, classname)
instance = klass(*args, **kw)

其中,module是模块对象,classname是带有类名的字符串,args是位置参数序列,kw是带有关键字参数的映射。你知道吗

要从字符串中获取模块名,请使用^{}动态导入:

import importlib

module = importlib.import_module(modulename)

您甚至可以接受最终类的虚线路径标识符,只需将其拆分为模块名和类:

modulename, _, classname = identifier.rpartition('.')

演示:

>>> import importlib
>>> identifier = 'collections.defaultdict'
>>> modulename, _, classname = identifier.rpartition('.')
>>> modulename, classname
('collections', 'defaultdict')
>>> args = (int,)
>>> kw = {}
>>> module = importlib.import_module(modulename)
>>> klass = getattr(module, classname)
>>> klass
<type 'collections.defaultdict'>
>>> instance = klass(*args, **kw)
>>> instance
defaultdict(<type 'int'>, {})

相关问题 更多 >