首页 > 代码库 > 函数参数自动解包

函数参数自动解包

函数参数自动解包

你使用*, **可以自动的对一个list,dict做函数参数,自动的解包

例子:

def draw_point(x, y):    # do some magicpoint_foo = (3, 4)point_bar = {y: 3, x: 2}draw_point(*point_foo)draw_point(**point_bar)

这是一个非常捷径的用法。

NOTE:

请看这两个程序的不同。。。

def cheeseshop(kind, *arguments, **keywords):    print "-- Do you have any", kind, "?"    print "-- I‘m sorry, we‘re all out of", kind    for arg in arguments:        print arg    print "-" * 40    keys = sorted(keywords.keys())    for kw in keys:        print kw, ":", keywords[kw]cheeseshop("Limburger", "It‘s very runny, sir.",           "It‘s really very, VERY runny, sir.",           shopkeeper=Michael Palin,           client="John Cleese",           sketch="Cheese Shop Sketch")

 

Python不单可以自动解包,也可以自动的形成tuple,dict数据结构作为函数参数。。

函数参数自动解包