Python:调用名称存储在变量中的构造函数 [英] Python: Call a constructor whose name is stored in a variable

查看:132
本文介绍了Python:调用名称存储在变量中的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下变量:

var = 'MyClass'

我想基于变量 var创建 MyClass 的对象 var()之类的东西。我该如何在Python中执行此操作?

I would like to create an object of MyClass based on the variable var. Something like var(). How can I do this in Python?

推荐答案

假设您也将class模块作为变量,则可以以下,您要 MyClass的类位于模块 my.module中:

Presuming you have the class' module as a variable as well, you can do the following, where the class you want "MyClass" resides in module "my.module":

def get_instance(mod_str, cls_name, *args, **kwargs):
    module = __import__(mod_str, fromlist=[cls_name])
    mycls = getattr(module, cls_name)

    return mycls(*args, **kwargs)


mod_str = 'my.module'
cls_name = 'MyClass'

class_instance = get_instance(mod_str, cls_name, *args, **kwargs)

此函数可让您获取任何类的实例,无论使用什么参数构造函数的需要,可以从程序中可用的任何模块中获取。

This function will let you get an instance of any class, with whatever arguments the constructor needs, from any module available to your program.

这篇关于Python:调用名称存储在变量中的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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