2013-02-18 107 views
0

我想寫一個函數,該函數將創建一個參數中指定的任何類的實例,並將用任意數量的參數調用該類。用Python中的任意參數創建一個類的實例?

這似乎並不工作:

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

我在做什麼錯?

編輯:夥計們我是個白癡。做這個函數的原因是,那些沒有訪問其他類的類仍然可以創建它們的實例,但實際上它們可以訪問其他類。所以沒關係。

+0

您是否嘗試過'tospawn(* args)'?或者'tospawn'是一個字符串? – Blender 2013-02-18 22:47:19

+2

「這似乎不起作用」 - 詳細說明。你會得到什麼錯誤?錯誤的確切文字是什麼? – Amber 2013-02-18 22:49:39

+0

Tospawn是一個字符串,但會有一個同名的類。這是錯誤:AttributeError:'模塊'對象沒有屬性'實例' – tesselode 2013-02-19 00:21:29

回答

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) 
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__ 
0

globals()返回帶有字符串鍵的字典。像

from collection import deque 

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

東西的工作,但下面將給出一個關鍵的錯誤

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

因爲雙端隊列爲一個類型,而不是一個字符串。

也許你可以這樣做:

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

我不認爲這將工作,因爲我傳遞該函數作爲第一個參數的字符串(與一個類相同的名稱)。如果我做了tospawn(* args),它會尋找一個名爲tospawn的類,而不是與tospawn的值同名的類。 – tesselode 2013-02-19 00:25:38

0

爲什麼不使用eval

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