Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #55903

Re: Understanding def foo(*args)

References <17945aea-21b6-45b5-9c09-e602143f755e@k4g2000pre.googlegroups.com>
Date 2011-01-30 11:54 -0800
Subject Re: Understanding def foo(*args)
From Chris Rebert <clp2@rebertia.com>
Newsgroups comp.lang.python
Message-ID <mailman.1473.1296417280.6505.python-list@python.org> (permalink)

Show all headers | View raw


On Sun, Jan 30, 2011 at 11:26 AM, sl33k_ <ahsanbagwan@gmail.com> wrote:
> Hi,
>
> I am struggling to grasp this concept about def foo(*args).

The interactive interpreter is your friend! Try experimenting with it next time!

http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists
That `def` defines a variadic function; i.e. a function which takes an
arbitrary number of positional arguments.
`args` will be a tuple of all the positional arguments passed to the function:
>>> def foo(*args):
...     print args
...
>>> foo(1)
(1,)
>>> foo(1,2)
(1, 2)
>>> foo(1,2,3)
(1, 2, 3)

If positional parameters precede the *-parameter, then they are
required and the *-parameter will receive any additional arguments:
>>> def qux(a, b, *args):
...     print 'a is', a
...     print 'b is', b
...     print 'args is', args
...
>>> qux(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: qux() takes at least 2 arguments (1 given)
>>> qux(1, 2)
a is 1
b is 2
args is ()
>>> qux(1, 2, 3)
a is 1
b is 2
args is (3,)
>>> qux(1, 2, 3, 4)
a is 1
b is 2
args is (3, 4)

> Also, what is def bar(*args, *kwargs)?

You meant: def bar(*args, **kwargs)

See http://docs.python.org/tutorial/controlflow.html#keyword-arguments
Basically, the **-parameter is like the *-parameter, except for
keyword arguments instead of positional arguments.

> Also, can the terms method and function be used interchangeably?

No. A method is function that is associated with an object (normally
via a class) and takes this object as its first argument (typically
named "self"). A function does not have any of these requirements.
Thus, all method are functions, but the reverse is not true.
(I'm ignoring complexities like classmethods and staticmethods for simplicity.)

Cheers,
Chris
--
http://blog.rebertia.com

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Understanding def foo(*args) Chris Rebert <clp2@rebertia.com> - 2011-01-30 11:54 -0800

csiph-web