question about function pointer

Nobody nobody at nowhere.com
Fri Feb 17 10:55:11 CET 2012


On Fri, 17 Feb 2012 16:53:00 +0900, Zheng Li wrote:

> def method1(a = None):
> 	print a
> 
> i can call it by
> method1(*(), **{'a' : 1})
> 
> I am just curious why it works and how it works?
> and what do *() and **{'a' : 1} mean?

In a function call, an argument consisting of * followed by an expression
of tuple type inserts the tuple's elements as individual positional
arguments. An argument consisting of ** followed by an expression of
dictionary type inserts the dictionary's elements as individual keyword
arguments.

So if you have:

	a = (1,2,3)
	b = {'a': 1, 'b': 2, 'c': 3}

then:

	func(*a, **b)

is equivalent to:

	func(1, 2, 3, a = 1, b = 2, c = 3)

> when I type *() in python shell, error below happens
> 
>   File "<stdin>", line 1
>     *()
>     ^
> SyntaxError: invalid syntax

The syntax described above is only valid within function calls.

There is a similar syntax for function declarations which does the reverse:

	> def func(*a, **b):
	    print a
	    print b

	> func(1, 2, 3, a = 1, b = 2, c = 3)
	(1, 2, 3)
	{'a': 1, 'c': 3, 'b': 2}





More information about the Python-list mailing list