2011-07-12 93 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