zoukankan      html  css  js  c++  java
  • 07-缺省参数

    缺省参数

    在调用函数时,缺省参数的值如果没有传入,则认为是默认值,带有默认值的参数一定要位于参数列表的最后面

    举例1:

    #-*- coding:utf-8 -*-
    
    def test(a,b):  #定义一个函数,传入a和b
        result = a+b
        print("result=%d"%result)
    
    test(11,22)  #调用函数并且给出实参
    test(22,22)
    test(33,22)
    
    root@ubuntu:/home/python/codes/python基础-05# python2 test.py 
    result=33
    result=44
    result=55

    在这个程序当中,我们发现是有缺陷的,为什么这样说呢?我们可以看到,在我们调用test函数时候,传入了两个参数,但是在第二个参数后面都是一样的,那么我们可想:因为第二个参数是一样的,那么我们能不能修改一下代码,让第二个参数有着默认参数呢,即当我们只传入一个参数的时候,第二个参数是默认的;当我们传入两个参数的时候,我们传过去的就是我们想要的呢?答案是可以

    #-*- coding:utf-8 -*-
    
    def test(a,b=22):  #此时的b=22就是缺省参数
        result = a+b
        print("result=%d"%result)
    
    test(11)
    test(22)
    test(33)
    
    root@ubuntu:/home/python/codes/python基础-05# python3 test.py 
    result=33
    result=44
    result=55

    举例2:

    在上节我们说过help()函数可以查看到函数的文档说明,让我们现在来看下:

    In [1]: help(print)
    
    Help on built-in function print in module builtins:
    
    print(...)
        print(value, ..., sep=' ', end='
    ', file=sys.stdout, flush=False)  #end='
    '就可以说明为什么我们打印出来的东西就一定会换行,因为它是缺省参数
        
        Prints the values to a stream, or to sys.stdout by default.
        Optional keyword arguments:
        file:  a file-like object (stream); defaults to the current sys.stdout.
        sep:   string inserted between values, default a space.
        end:   string appended after the last value, default a newline.
        flush: whether to forcibly flush the stream.

    举例3:

    In [2]: def test(a,b=22,c=33):  #定义一个函数,此时b和c是缺省参数,即默认值
       ...:     print(a)
       ...:     print(b)
       ...:     print(c)
       ...:     
    
    In [3]: test(11,c=44)  #调用函数,并传入a的值为11,c的值为44
    11
    22
    44
  • 相关阅读:
    php知识点
    CommonsChunkPlugin知识点
    待学习
    svn知识点
    es6知识点
    webpack2新特性
    排序算法
    交流措辞
    js继承
    多行编辑软件
  • 原文地址:https://www.cnblogs.com/xiaoyafei/p/8556160.html
Copyright © 2011-2022 走看看