Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用带有动态参数的函数调用时的元组索引_Python - Fatal编程技术网

Python 使用带有动态参数的函数调用时的元组索引

Python 使用带有动态参数的函数调用时的元组索引,python,Python,给我索引器错误:元组索引超出范围 为什么呢?如何获取该元组的值?您只传入了一个参数(整个元组(2,3)),因此只存在arg[0];如果您想将元组值作为单独的参数,请使用*args调用语法应用它们: >>> class Test(object): >>> def test(self,*arg): >>> print(arg[0],arg[1]) >>> p = Test() >>> t =

给我索引器错误:元组索引超出范围


为什么呢?如何获取该元组的值?

您只传入了一个参数(整个元组
(2,3)
),因此只存在
arg[0]
;如果您想将元组值作为单独的参数,请使用
*args
调用语法应用它们:

>>> class Test(object):
>>>    def test(self,*arg):
>>>       print(arg[0],arg[1])
>>> p = Test()
>>> t = 2,3
>>> p.test(t)
另一种方法是在函数定义中不使用
*arg
catchall参数:

p.test(*t)
现在,函数有两个正常的位置参数,
self
arg
。您只能传入一个参数,如果这是元组,
arg[0]
arg[1]
将按预期工作。

使用演示类:

def test(self, arg):
执行此操作时:

>>> class Test(object):
>>>    def test(self,*arg):
>>>       print(arg[0],arg[1])
>>> p = Test()
>>> t = 2,3
>>> p.test(t)
arg
的值为
[(1,2),]

执行此操作时:

>>> class Test(object):
>>>    def test(self,*arg):
>>>       print(arg[0],arg[1])
>>> p = Test()
>>> t = 2,3
>>> p.test(t)
arg
的值为
[1,2]

函数中的
*
意味着所有剩余参数(非关键字)都会被放入一个列表中

在第一种情况下,您发送的
(1,2)
只有一个参数。在第二种情况下,使用
*
将元组设置为单独的参数,因此您可以发送
1
2

有关这方面的完整文档,请参阅这篇Python文章:
@AFwcxx它正在传递
(2,3)
@AFwcxx:不,它将传递值
(2,3)
<代码>元组对象也是值。@MartijnPieters,如果它正在传递(2,3)。那么arg[0]和arg[1]不应该生成2,3吗?这里我想我要回答这个问题。干得好Martijn!:D@AFwcxx如果您将函数定义为
def test(self,arg):