• 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 !
     
  • 相关阅读:
    函数二 10
    函数初识 09
    文件操作 08
    数据类型的补充 day07
    小数据池 深浅copy 集合
    python Mysql 多条件查询
    ElasticSearch Python 基本操作
    用PyInstaller把Python代码打包成单个独立的exe可执行文件
    python 编译EXE文件
    Git 创建新分支检查分支
  • 原文地址:https://www.cnblogs.com/geeklove01/p/9122303.html
Copyright © 2020-2023  润新知