Python笔记(20)函数式编程之参数详解

    技术2026-03-19  10

    #!/user/bin/env python # -*- coding:utf-8 -*- # author:berlin # 5、函数的返回值 # def test1(): # print('test1') # # def test2(): # print('test2') # return 0 # # def test3(): # print('test3') # return 1,'hello',['ganbailin','lilingling'],{'name':'gbl'} # # print(test1()) # print(test2()) # print(test3()) # 6、函数的调用 # (1)函数方法test()执行时,()表示调用函数test,()内可以有参数也可以没有。 # 参数有: # 【1】形参和实参 # 形参:形式参数,不是实际存在的,是虚拟变量,在定义函数和函数体的时候使用形参,目的是在函数调用 # 时接收实参(实参个数,类型应与实参一一对应)。 # 实参:实际参数,调用函数时传给函数的参数,可以是常量、变量、表达式、函数。传给形参。 # 区别: # 形参是虚拟的,不占用内存空间。形参变量只有在调用时才分配内存单元。实参是一个变量,占用内存空间, # 数据传送单向,实参传给形参,不能形参传给实参。 # 【2】位置参数和关键字(标准调用:实参和形参位置一一对应;关键字调用:位置无需固定) # 【3】默认参数 # 【4】参数组 # 示例1:位置参数 # x和y代表形参;1和2代表实参。形参和实参是一一对应的,并且这样也是位置参数调用样例。 # def test(x,y): # print(x) # print(y) # # test(1,2) # 示例2:关键字 # x和y代表形参;1和2代表实参。形参和实参不需一一对应的,并且这样也是关键字调用样例。 # def test(x,y): # print(x) # print(y) # # test(y=2,x=1) # 示例3:当既有位置参数、也有关键字时 # 当既有位置参数、也有关键字时。调用时,以位置参数优先,并且关键字不能写在位置参数之前 # def test(x,y,z): # print(x) # print(y) # print(z) # # test(2,y=4,3) 错误的调用示例 # test(2,y=1,z=6) #示例4:默认参数 # 默认参数特点:调用参数的时候,默认参数非必须传递。 #用途:1、默认安装值 2、连接数据库时的默认值等 # def test(x,y=2): # print(x) # print(y) # # test(1) #当y没有重新赋值,那么y默认等于2 # test(1,3) #当y重新赋值了,那么y等于3 # 示例5:参数组 # (1)*args:把N个位置参数,转换成元组的方式 # def test(*args): # *代表参数组,调用时把1,2,3,4,5,5,6都传给args # print(args) # # test(1,2,3,4,5,5,6) # test(*[1,2,3,4,5,5,6]) #args = tuple([1,2,3,4,5,5,6]) # (2) # def test(x,*args): # 调用时,会按照位置来,1传给x。2,3,4,5,5,6都传给args # print(x) # print(args) # # test(1,2,3,4,5,5,6) # (3)**kwargs:把N个关键字参数,转换成字典的方式 # def test(**kwargs): # print(kwargs) # print(kwargs['name']) # print(kwargs['age']) # print(kwargs['sex']) # # test(name='ganbailin',age=26,sex='M') # test(**{'name':'ganbailin','age':26,'sex':'M'}) # (5) # def test(name,**kwargs): # print(name) # print(kwargs) # # test('gan',age=26,sex='M') # (6) # def test(name,age=26,**kwargs): # print(name) # print(age) # print(kwargs) # # test('gan',high=173,sex='M') # (7) # def test(name,age=26,**kwargs): # print(name) # print(age) # print(kwargs) # # test('gan',high=173,sex='M',age=31) # (8) # def test(name,age=26,*args,**kwargs): # print(name) # print(age) # print(args) # print(kwargs) # # test('gan',31,2,3,4,5,high=173,sex='M') # 7、前向引用 # 函数action体内嵌套某一函数logger,该logger的声明必须早于action函数的调用,否则报错。 # def action(): # print('in the action') # logger() # action() # # 报错:global name 'logger' is not defines # def logger(): # print('in the logger') # def action(): # print('in the action') # logger() # action() # # def action(): # print('in the action') # logger() # def logger(): # print('in the logger') # action() # 属性调用
    Processed: 0.011, SQL: 9