>>> class Test(object):
>>> def test(self,*arg):
>>> print(arg[0],arg[1])
>>> p = Test()
>>> t = 2,3
>>> p.test(t)
gives me IndexError: tuple index out of range
why is that? and how do i get the value for that tuple?
You passed in just one argument (the whole tuple (2, 3)
), so only arg[0]
exists; if you meant the tuple values to be separate arguments, apply them with the *args
call syntax:
p.test(*t)
The alternative is to not use the *arg
catchall argument in your function definition:
def test(self, arg):
Now your function has two normal positional arguments, self
and arg
. You can only pass in one argument, and if that is your tuple, arg[0]
and arg[1]
will work as expected.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.