• Python档案袋(函数与函数装饰器 )


    特点:代码复用、可扩展、保持一致性

    函数简单的实现,返回值的不同:

     1 #定义方法
     2 def funx1():
     3     pass
     4 
     5 def funx2():
     6     return 0
     7 
     8 def funx3():
     9     return 11,12,[33,88],{"xx":99}
    10 
    11 def funx411():
    12     return ("------funx411111111------")
    13 
    14 
    15 def funx4():
    16     return funx411
    17 
    18 #调用方法1
    19 #返回:None
    20 print(funx1())
    21 
    22 #调用方法2
    23 #返回:0
    24 print(funx2())
    25 
    26 #调用方法3
    27 #返回元组:(11, 12, [33, 88], {'xx': 99})
    28 print(funx3())
    29 
    30 #调用方法4
    31 #返回函数地址,加括号就可运行
    32 funx40=funx4();
    33 #输出:------funx411111111------
    34 print(funx40())

    函数简单的实现,形参的不同:

     1 def funx1(x,y):
     2     print("x=%s,y=%s"%(x,y))
     3 
     4 #默认参数
     5 def funx2(x2,y2=10):
     6     print("x=%s,y=%s" % (x2, y2))
     7 
     8 # *args可接收多个不固定位置参数,转换为元组
     9 def funx3(x1,y1,*args):
    10     print(x1) #输出11
    11     print(y1) #输出13
    12     print(len(args)) #输出个数,2
    13     print(args) #输出全部值,以元组方式,(19, 18)
    14 
    15 # *kwargs可接收多个不固定关键字参数,转换为字典
    16 def funx4(**kwargs):
    17     print(kwargs)
    18 
    19 #与形参一一对应
    20 funx1(11,22)
    21 #与形参位置无关
    22 funx1(y=88,x=99)
    23 #默认值可以不传递值
    24 funx2(110)
    25 funx3(11,13,19,18)
    26 funx4(user="dong",name="dongxiaodong",age=100)

    递归函数:

    #递归函数
    def funx1(intx):
        
        intx-=1
        print(intx)
        
        if intx >0:
            funx1(intx) #再次调用自己
    
    funx1(10)

    高阶函数:

    函数作为参数进行传递

    def addx(x,y,funx):
        return funx(x)+funx(y)
    
    res=addx(-5,1,abs) #abs的绝对值运算函数
    print(res) #输出:6

    函数装饰器:

    本质是函数,用来装饰其他函数(给其他函数添加功能)

    注意:

    1、不可修改被装饰函数源代码

    2、不可更改被装饰函数的调用方式

     1 import time
     2 
     3 #装饰器
     4 def decofun(func): #decofun(funx1)
     5   def deco(*args,**kwargs):#可支持多个位置参数和关键字参数传递
     6      starttime=time.time()#获的开始取时间戳
     7      func(*args,**kwargs) #运行函数
     8      stoptime=time.time()
     9      print("函数运算时间为:%f"%(stoptime-starttime))
    10   return deco #返回函数地址
    11 
    12 @decofun  #相当于:funx1=decofun(funx1)
    13 def funx1():
    14     time.sleep(1)
    15     print("----funx1----")
    16 
    17 @decofun  #相当于:funx2=decofun(funx2)
    18 def funx2(x,y):
    19     print(x,"---funx2---",y)
    20 
    21 #funx1=decofun(funx1)
    22 funx1() #调用函数
    23 funx2(y=12,x=16)#调用函数
  • 相关阅读:
    对于高并发短连接造成Cannot assign requested address解决方法
    virtualbox迁移已建虚机存储磁盘方法
    httpd:RSA certificate configured for SERVER does NOT include an ID which matches the server name
    解决服务不断重启挂掉问题
    tbb静态库编译
    su和su
    ubuntu18.04 mariadb start失败
    如何修复“sshd error: could not load host key”
    [LeetCode]Gas Station
    Java多态的一些陷阱
  • 原文地址:https://www.cnblogs.com/dongxiaodong/p/10493603.html
Copyright © 2020-2023  润新知