question about function pointer

Z

Zheng Li

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?

when I type *() in python shell, error below happens

File "<stdin>", line 1
*()
^
SyntaxError: invalid syntax
 
N

Nobody

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}
 
8

88888 Dihedral

在 2012å¹´2月17日星期五UTC+8下åˆ5æ—¶55分11秒,Nobody写é“:
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)


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}

In the functional programming view, 2 to 5
object parameters are enough to invoke a function.

But the tuple and dictionary packing and unpacking
are not free in the run time.


Enhancement to operations of basic types in Python can speed up everything..
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top