[英]Given a class type how do I create an instance in Python?
Let's say I have this : 假设我有这个:
class whatever(object):
def __init__(self):
pass
and this function: 和这个功能:
def create_object(type_name):
# create an object of type_name
I'd like to be able to call the create_object
like this: 我希望能够这样调用
create_object
:
inst = create_object(whatever)
and get back an instance of whatever
. 并取回的一个实例
whatever
。 I think this should be doable without using eval
, I'd like to know how to do this. 我认为无需使用
eval
就可以做到这一点,我想知道如何做到这一点。 Please notice that I'm NOT using a string as a parameter for create_object
. 请注意,我没有使用字符串作为
create_object
的参数。
The most obvious way: 最明显的方法:
def create_object(type_name):
return type_name()
def create_object(typeobject):
return typeobject()
As you so explicitly say that the arg to create_object
is NOT meant to be a string, I assume it's meant to be the type object itself, just like in the create_object(whatever)
example you give, in which whatever
is indeed the type itself. 当你这样明确地说,对Arg的
create_object
并不意味着是一个字符串,我认为它的意思是类型对象本身,就像在create_object(whatever)
你给例子,其中whatever
确实是该类型本身。
If I understand correctly, what you want is: 如果我理解正确,那么您想要的是:
def create_object(type_name, *args):
# create an object of type_name
return type_name(*args)
inst = create_object(whatever)
I don't really know why you want to do this, but would be interesting to hear from you what are your reasons to need such a construct. 我真的不知道您为什么要这样做,但是很高兴听到您的消息,您为什么需要这种构造。
def create_object(type_name):
return type_name()
you can of course skip the function altogether and create the instance of whatever
like this: 当然你也可以完全跳过功能,并创建实例
whatever
是这样的:
inst = whatever()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.