在Python中用任意参数创建一个类的实例?

时间:2013-02-18 22:46:02

标签: python class instance

我想编写一个函数,它将创建一个参数中指定的任何类的实例,并使用任意数量的参数调用该类。

这似乎不起作用:

def spawn(tospawn, *args):
    global current_state
    current_state.instance.append(globals()[tospawn](*args))

我做错了什么?

编辑:伙计们,我是个白痴。创建此函数的原因是,无法访问其他类的类仍然可以创建它们的实例,但它们实际上可以访问其他类。所以没关系。

4 个答案:

答案 0 :(得分:0)

class MyClass(object):
    def __init__(self, a, b, c, d=None):
        print a, b, c, d

args, kwargs = [1,2], {'c':3, 'd':4}
tospawn = MyClass

tospawn(*args, **kwargs)

答案 1 :(得分:0)

你无法从全局变量中获取类; tospawn是一种类型,而不是字符串。类型是第一类对象,您可以直接使用它们。

至于整个代码,我会亲自用classmethod做这个。

class Spawner:
    __spawned__ = []

    @classmethod
    def spawn(cls, tospawn, *args, **kwargs):
        obj = tospawn(*args, **kwargs)
        cls.__spawned__.append(obj)

class TestClass:
    def __init__(self, *args):
        print args

Spawner.spawn(TestClass, "these", "are", "args")
print Spawner.__spawned__

答案 2 :(得分:0)

globals()返回带字符串键的字典。像

这样的东西
    from collection import deque

    args = range(20), 3
    a = globals()['deque'](*args)

将起作用,但以下将给出一个关键错误

    a = globals()[deque](*args)

因为deque是一个类型而不是字符串。

也许你可以这样做:

def spawn(tospawn, *args):
    global current_state
    try:
        current_state.instance.append(globals()[tospawn](*args))
    except KeyError:
        current_state.instance.append(tospawn(*args))

答案 3 :(得分:0)

为什么不使用eval

def spawn(tospawn, *args):
     global current_state
     current_state.instance.append(eval("{}(*{})".format(tospawn, args)))