zoukankan      html  css  js  c++  java
  • Python定义参数数量可变的method的问题

    根据文档(https://docs.python.org/2/tutorial/controlflow.html#more-on-defining-functions)

    介绍了三种方法

    1 Default Argument Values 

    The most useful form is to specify a default value for one or more arguments. This creates a function that can be called with fewer arguments than it is defined to allow

    比较简单,就是给每个method中的参数赋一个默认值

    The default values are evaluated(赋值) at the point of function definition in the defining scope, so that

    i = 5
    
    def f(arg=i):
        print arg
    
    i = 6
    f()

    will print 5.

    Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:

    def f(a, L=[]):
        L.append(a)
        return L
    
    print f(1)
    print f(2)
    print f(3)

    this will print:

    [1]
    [1, 2]
    [1, 2, 3]

    If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:

    def f(a, L=None):
        if L is None:
            L = []
        L.append(a)
        return L

    2 Arbitrary Argument Lists

    使用*args的时候,将传入的参数pack成tuple来处理:

    def foo(*args):
      for a in args:
        print a
      print 'end of call'
    
    lst = [1,2,3]
    foo(lst)    
    foo(*lst)
    
    #output:
    [1, 2, 3]
    end of call
    1
    2
    3
    end of call

    3 Keyword Arguments

    使用**kw的时候,将传入的所有的keyword arguments来pack成dict处理:

    When a final formal parameter of the form **name is present, it receives a dictionary (see Mapping Types — dict) containing all keyword arguments except for those corresponding to a formal parameter.

    对这句话的解释:

    def bar(name='Jack', age=21, **kw):
      print kw
    
    bar(a=1, b=2)  # {'a': 1, 'b': 2}
    bar(name='Lucy', job='doctor') # {'job': 'doctor'}

    stackoverflow(https://stackoverflow.com/questions/33542959/why-use-packed-args-kwargs-instead-of-passing-list-dict)总结的*,**的适用场景 :

    *args/**kwargs has its advantages, generally in cases where you want to be able to pass in an unpacked data structure, while retaining the ability to work with packed ones.

    Of course, if you expect the function to always be passed multiple arguments contained within a data structure, as sum() and str.join() do, it might make more sense to leave out the *syntax.

    关于 Unpacking Argument Lists的解释:

    The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments.

    举例:

    >>> range(3, 6)             # normal call with separate arguments
    [3, 4, 5]
    >>> args = [3, 6]
    >>> range(*args)            # call with arguments unpacked from a list
    [3, 4, 5]

    In the same fashion, dictionaries can deliver keyword arguments with the **-operator:

    >>> def parrot(voltage, state='a stiff', action='voom'):
    ...     print "-- This parrot wouldn't", action,
    ...     print "if you put", voltage, "volts through it.",
    ...     print "E's", state, "!"
    ...
    >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
    >>> parrot(**d)
    -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
     
  • 相关阅读:
    VBA中使用计时器的两种方法
    好的关卡离不开优秀的团队
    如何从无到有做一个好关卡?
    性能优化总结
    用超链接提交表单,实现在动态网页的url中隐藏参数
    js 中使用el表达式 关键总结:在js中使用el表达式一定要使用双引号
    js中getBoundingClientRect的作用及兼容方案
    IE10、IE11和Microsoft Edge的Hack
    CSS Hack大全-教你如何区分出IE6-IE10、FireFox、Chrome、Opera
    点击a标签,跳转到iframe中,并在iframe中显示指定的页面
  • 原文地址:https://www.cnblogs.com/geeklove01/p/9122303.html
Copyright © 2011-2022 走看看