Python将*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])
4 个回答
0
如果你想要了解和@simon的解决方案类似的内容,可以看看这个:
def test_args(*args):
lists = [*args]
print(lists)
test_args([7],'eight',[[9]])
运行结果是:
[[7], 'eight', [[9]]]
11
这里有一段我在sentdex教程中学到的代码,跟这个内容有关:
https://www.youtube.com/watch?v=zPp80YM2v7k&index=11&list=PLQVvvaa0QuDcOdF96TBtRtuQksErCEBYZ
试试这个:
def test_args(*args):
lists = [item for item in args]
print lists
test_args('Sun','Rain','Storm','Wind')
结果是:
['Sun', 'Rain', 'Storm', 'Wind']
32
没什么特别复杂的:
def __init__(self, *args):
Parent.__init__(self, list(args))
在__init__
这个方法里,变量args
其实就是一个元组,里面装的是传进来的所有参数。实际上,如果你不需要把它变成列表的话,可以直接用Parent.__init__(self, args)
。
顺便提一下,使用super()
比直接用Parent.__init__()
更好。