Python将* args转换为列表

时间:2013-03-18 23:49:44

标签: python arrays python-2.7 args

这就是我要找的:

def __init__(self, *args):
  list_of_args = #magic
  Parent.__init__(self, list_of_args)

我需要将* args传递给单个数组,以便:

MyClass.__init__(a, b, c) == Parent.__init__([a, b, c])

3 个答案:

答案 0 :(得分:13)

没有什么太神奇了:

def __init__(self, *args):
  Parent.__init__(self, list(args))

__init__内部,变量args只是传入任何参数的元组。实际上你可以只使用Parent.__init__(self, args),除非你真的需要它是一个列表。

作为旁注,使用super()优于Parent.__init__()

答案 1 :(得分:1)

我在sentdex教程中提到的这段代码处理了这个:

assylias's

试试这个:

def test_args(*args):
    lists = [item for item in args]
    print lists

test_args('Sun','Rain','Storm','Wind')

结果:

  

['太阳','雨','风暴','风']

答案 2 :(得分:0)

如果您正在寻找与@simon解决方案方向相同的东西,那么:

def test_args(*args): lists = [*args] print(lists) test_args([7],'eight',[[9]])

结果:

  

[[7],'八',[[9]]]