2011-07-12 139 views
0

我遇到了問題。我有一個隨機元素的數組,我有對象(最大數組=對象的最大attr)。但如果我使用:Python,聲明對象的變量數attr

breadcrumbs = breadObject(element[0],element[1],element[2]) 

但如果我有隻有2個元素([0] [1])的數組我有錯誤。

我嘗試:

exec("breadcrumbs = breadObject(%s)"%string_bread) 
    return breadObject 

其中string_bread是前。 STR(「部件1」,「element2的」),但它返回錯誤:

name 'breadObject' is not defined

+0

你提的問題是非常困惑。你想達到什麼目的?如何定義'breadObject'?你在這裏嘗試的這個黑暗的'exec'-voodoo是什麼?我想你應該閱讀[教程](http://docs.python.org/tutorial/),然後再嘗試任何東西 - 你似乎缺乏基礎知識。 –

+0

你爲什麼要返回'breadObject'而不是'breadcrumbs'?如果你嘗試'breadcrumbs = breadObject(eval(string_bread))'會發生什麼? @ Space_C0wb0y:如果我的解釋是正確的,他看起來像是將他的函數的參數作爲一個字符串來獲取。但是從主要觀點來看,這就是他根據參數的數量得到一個錯誤。 user840724,你能發佈對象定義爲Space_C0wb0y請求嗎?或者至少發佈'breadObject'的'__init__'? – JAB

回答

2

不知道,正確地理解你,但想你可以使用下面的語法:

breadcrumbs = breadObject(*element) 

Arbitrary number of arguments can be collected with *args syntax and an arbitrary number of keyword arguments can be collected as a dictionary with **kwargs syntax.:

def function(*args, **kwargs): 
    assert isinstance(args, tuple), 'args is always a tuple' 
    assert isinstance(kwargs, dict), 'kwargs is always a dictionary' 

*args and **kwargs can be used to call functions with multiple arguments/keyword arguments from a tuple or dictionary