• Python学习札记(十三) Function3 函数参数二


    参考:函数参数

    Note

    A.关键字参数:

    1.关键字参数:**kw

    可变参数允许你传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple。而关键字参数允许你传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict。

    2.支持只传入必选参数;也可以传入任意数目的可选参数,如下例。

    eg.

    #!/usr/bin/env python3
    
    def my_func(name, age, **kw) :
    	print('name:', name, 'age:', age, 'else:', kw)
    
    

    test

    >>> from function3 import my_func
    
    >>> my_func('Chen', 20)
    name: Chen age: 20 else: {}
    
    >>> my_func('Chen', 20, prof='Student')
    name: Chen age: 20 else: {'prof': 'Student'}
    
    >>> my_func('Chen', 20, prof='Student', city='FuZhou')
    name: Chen age: 20 else: {'prof': 'Student', 'city': 'FuZhou'}
    

    3.关键字参数的作用:”试想你正在做一个用户注册的功能,除了用户名和年龄是必填项外,其他都是可选项,利用关键字参数来定义这个函数就能满足注册的需求。“

    4.当然,也可以选择在传入参数的时候直接传入一个dict的内容。这里容易出错,我就翻车了。

    eg.

    >>> dic = {'prof' : 'Student', 'city' : 'FuZhou'}
    >>> my_func('Chen', 20, dic['prof'], dic['city'])
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: my_func() takes 2 positional arguments but 4 were given
    
    >>> my_func('Chen', 20, dic)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: my_func() takes 2 positional arguments but 3 were given
    

    第一句错误的原因,是因为传入dic['prof']相当于传入'Student',即一个字符串,这很明显与函数定义的参数不符;第二句同上,只不过由传入字符串变成了传入一个dict。

    正确的方法应该是value_name=dict[key]

    eg.

    >>> my_func('Chen', 20, prof=dic['prof'])
    name: Chen age: 20 else: {'prof': 'Student'}
    
    >>> my_func('Chen', 20, prof=dic['prof'], city=dic['city'])
    name: Chen age: 20 else: {'prof': 'Student', 'city': 'FuZhou'}
    

    5.如果想直接传入dict,方法也很简单,加上两个星号*

    刚才的错误:

    >>> my_func('Chen', 20, dic)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: my_func() takes 2 positional arguments but 3 were given
    

    修正:

    >>> my_func('Chen', 20, **dic)
    name: Chen age: 20 else: {'prof': 'Student', 'city': 'FuZhou'}
    

    **dic表示把dic这个dict的所有key-value用关键字参数传入到函数的**kw参数,kw将获得一个dict,注意kw获得的dict是dic的一份拷贝,对kw的改动不会影响到函数外的dic。

    B.命名关键字参数

    1.定义了关键字参数的函数允许用户传入多个关键字key-value值,如果我们想要在函数里面查看一个key是否在传入的dict中,可以通过if···in···的方法查看。

    eg.

    #!/usr/bin/env python3
    
    def my_func(name, age, **kw) :
    	
    	if 'prof' in kw :            # Hint: 'prof' => ''
    		print('prof in')
    
    	if 'city' in kw :
    		print('city in')
    
    	print('name:', name, 'age:', age, 'else:', kw)
    
    

    output

    >>> from function3 import my_func
    >>> dic = {'prof' : 'Student', 'city' : 'FuZhou'}
    >>> my_func('Chen', 20, **dic)
    prof in
    city in
    name: Chen age: 20 else: {'city': 'FuZhou', 'prof': 'Student'}
    >>> 
    

    2.如果要限制关键字参数的名字,就可以用命名关键字参数,例如,只接收city和prof作为关键字参数。

    方法:

    my_func(name, age, *, prof, city)
    

    *作为分隔符,指定传入的关键字参数key必须是prof和city。

    使用命名关键字参数时,要特别注意,如果没有可变参数,就必须加一个*作为特殊分隔符。如果缺少*,Python解释器将无法识别位置参数和命名关键字参数。

    eg.

    def my_func2(name, age, *, prof, city) :
    
    	print(name, age, prof, city)
    
    

    output

    >>> from function3 import my_func2
    >>> my_func2('Chen', 20, prof='Student', city='FuZhou')
    Chen 20 Student FuZhou
    

    注意:指定了关键字参数的key之后,传入的关键字参数数目必须匹配,并且必须是 key=value 的形式。

    命名关键字参数必须传入参数名。

    eg.

    >>> my_func2('Chen', 20, prof='Student')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: my_func2() missing 1 required keyword-only argument: 'city'
    
    >>> my_func2('Chen', 20)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: my_func2() missing 2 required keyword-only arguments: 'prof' and 'city'
    
    >>> my_func2('Chen', 20, 'Student', 'FuZhou')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: my_func2() takes 2 positional arguments but 4 were given
    

    3.命名关键字支持默认参数,在调用时,可以不传入默认参数的值。

    C.参数组合

    在Python中定义函数,可以用必选参数、默认参数、可变参数、关键字参数和命名关键字参数,这5种参数都可以组合使用。但是请注意,参数定义的顺序必须是:必选参数、默认参数、可变参数(*[···] or *list_name)、命名关键字参数和关键字参数(**{···} or **dict_name)。

    eg.

    def my_func3(a, b, c=0, *d, **e) :
    	print(a, b, c, d, e)
    

    output

    >>> my_func3('Chen', 20)
    Chen 20 0 () {}
    
    >>> my_func3('Chen', 20, 100)
    Chen 20 100 () {}
    
    >>> my_func3('Chen', 20, 100, *['Li', 'Wang'], **{'Li' : 'num1', 'Wang' : 'num2'})
    Chen 20 100 ('Li', 'Wang') {'Wang': 'num2', 'Li': 'num1'}
    
    >>> 
    

    在函数调用的时候,Python解释器自动按照参数位置和参数名把对应的参数传进去。

    也就出现了原文传入一个tuple和一个dict,解释器也正常输出的情况:

    >>> t1 = ('Li', 100, 99, 'Wang')
    
    >>> d1 = {'Wang' : 'num2', 'Li' : 'num1'}
    
    >>> my_func3(*t1, **d1)
    Li 100 99 ('Wang',) {'Wang': 'num2', 'Li': 'num1'}
    
    >>> t2 = ('Li', 100, 'Wang')
    
    >>> my_func3(*t2, **d1)
    Li 100 Wang () {'Wang': 'num2', 'Li': 'num1'}        # 按位置解释
    
    >>> t3 = ['Li', 100, 'Wang']
    
    >>> my_func3(*t3, **d1)
    Li 100 Wang () {'Wang': 'num2', 'Li': 'num1'}        # 传入一个list和一个tuple也可以
    
    >>> 
    

    2017/1/31

  • 相关阅读:
    AngularJs轻松入门(三)MVC架构
    使用regasm注册.net com组件出现不是有效的.net程序集的解决办法
    AngularJs轻松入门(二)数据绑定
    基于服务的并行系统的通讯方式探讨
    日志文件支持unicode字符的做法
    一个软件构建系统的设想
    C/C++中printf和C++中cout的输出格式
    gch文件学习
    《C++ Primer》笔记-#include,#ifndef
    Linux makefile 教程 非常详细,且易懂
  • 原文地址:https://www.cnblogs.com/qq952693358/p/6359044.html
Copyright © 2020-2023  润新知