use*_*419 1 python function args
寻找有关如何使用 *args 正确解压缩其他函数中的返回参数的指导?这是代码;
#!/usr/bin/python
def func1():
test1 = 'hello'
test2 = 'hey'
return test1, test2
def func2(*args):
print args[0]
print args[1]
func2(func1)
Run Code Online (Sandbox Code Playgroud)
我收到的错误信息;
<function func1 at 0x7fde3229a938>
Traceback (most recent call last):
File "args_test.py", line 19, in <module>
func2(func1)
File "args_test.py", line 17, in func2
print args[1]
IndexError: tuple index out of range
Run Code Online (Sandbox Code Playgroud)
我已经尝试了一些事情,args()但没有成功。尝试打开包装时我做错了什么?
你没有调用func,所以你func2实际上得到了一个参数,它是一个函数对象。将您的代码更改为:func2(*func1())
# While you're at it, also unpack the results so hello and hey are interpreted as 2 separate string arguments, and not a single tuple argument
>>> func2(*func1())
hello
hey
>>> func2(func1)
<function func1 at 0x11548AF0>
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
func2(func1)
File "<pyshell#19>", line 4, in func2
print args[1]
IndexError: tuple index out of range
Run Code Online (Sandbox Code Playgroud)
以供参考:
>>> func1
<function func1 at 0x11548AF0>
>>> func1()
('hello', 'hey')
>>>
Run Code Online (Sandbox Code Playgroud)