zoukankan      html  css  js  c++  java
  • 函数参数自动解包

    函数参数自动解包

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

    例子:

    def draw_point(x, y):
        # do some magic
    
    point_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数据结构作为函数参数。。

  • 相关阅读:
    17.CSS 文本属性和字体属性
    15.CSS 浮动
    D. Same GCDs
    B. Infinite Prefixes
    D. 0-1 MST
    lambda表达式复习
    D. New Year and Conference
    C. New Year and Permutation
    D. Dr. Evil Underscores
    D. Minimax Problem
  • 原文地址:https://www.cnblogs.com/tom-zhao/p/4025943.html
Copyright © 2011-2022 走看看