python中使用缺省函数的示例分析

小编给大家分享一下python中使用缺省函数的示例分析,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!

在函数参数中,除了常规参数还有缺省参数,即缺省参数有一个默认值,如果外部调用该函数没有给缺省参数传递参数,该形参直接取默认参数值;如果外部调用时给缺省参数传递了参数,那么该形参的值应该等于外部传递的参数,带有缺省参数的函数也被称为缺省函数,示例代码如下:

def cusom_print4(x,y=2,z=3): # x=2,z=3 缺省参数
 print("cusom_print4 : x={}".format(x))
 print("cusom_print4 : y={}".format(y))
 print("cusom_print4 : z={}".format(z))
 print("***"*20)
 
cusom_print4(1)
cusom_print4(1,4)
cusom_print4(1,4,3)

输出结果:

cusom_print4 : x=1
cusom_print4 : y=2
cusom_print4 : z=3
************************************************************
cusom_print4 : x=1
cusom_print4 : y=4
cusom_print4 : z=3
************************************************************
cusom_print4 : x=1
cusom_print4 : y=4
cusom_print4 : z=3
************************************************************

缺省函数的注意事项

缺省函数的定义位置

必须保证带有默认值的缺省函数在参数列表末尾

def print_info(name,title="",gender=True):
    """
 
    :param title: 职位
    :param name: 班上同学的姓名
    :param gender: True 男生 False 女生
    """
    gender_text="男生"
 
    if not gender:
        gender_text="女生"
 
    print("[%s] %s 是 %s" %(name,title,gender_text))
 
# 假设班上的同学,男生居多!
# 提示:在指定缺省参数的默认值时,应该使用最常见的值作为默认值
# 如果一个参数的值不能确定,则不应该设置默认值,具体的数值在调用函数时,向外界传递
print_info("小明",gender=True)

看完了这篇文章,相信你对python中使用缺省函数的示例分析有了一定的了解,想了解更多相关知识,欢迎关注行业资讯频道,感谢各位的阅读!