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

给我 IndexError: tuple index out of range

这是为什么?以及如何获得该元组的值?

4

2 回答 2

6

你只传入了一个参数(整个 tuple (2, 3)),所以只arg[0]存在;如果您的意思是元组值是单独的参数,请使用*args调用语法应用它们:

p.test(*t)

另一种方法是不在*arg函数定义中使用catchall 参数:

def test(self, arg):

现在你的函数有两个正常的位置参数,selfarg. 您只能传入一个参数,如果那是您的元组,arg[0]并且arg[1]将按预期工作。

于 2013-10-24T13:03:22.193 回答
1

Using your demo class:

>>> class Test(object):
>>>    def test(self,*arg):
>>>       print(arg[0],arg[1])

When doing this:

>>> p = Test()
>>> t = 2,3
>>> p.test(t)

arg will have a value of [(1,2),]

When doing this:

>>> p = Test()
>>> t = 2,3
>>> p.test(*t)

arg will have a value of [1,2]

The * in the function means that all remaining arguments (non-keyword) are put into a list for you.

In the first case you send (1,2) has a single argument. In the second case the tuple is made into individual arguments using the * thus you send in 1 and 2.

For complete documentation on this refer to this Python article: http://docs.python.org/2/reference/expressions.html#calls

于 2013-10-24T13:17:39.623 回答