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 !
     
  • 相关阅读:
    7月25 SVN 提交报错 | mybatis like | 数据库字段设计 | 打包打小包
    7月24 springboot 打包打小包 | mybatis 逆向工程 | 接口返回数据 | 启动打包注意事项 | springboot redis 引入
    7月20号 添加字段报错 | 密码加密与传输
    7月19 登录失败 错误次数 | 字段类型被修改bug | 日志
    7月14 Enity对象的抽取
    7月13 mybatis调用存储过程
    7月12 导入项目到svn | logback配置日志输出
    7月11 配置数据库自己挖坑 | 代码覆盖率测试 | MockMvc 测试用例
    书架
    试题库问题
  • 原文地址:https://www.cnblogs.com/geeklove01/p/9122303.html
Copyright © 2011-2022 走看看