zoukankan      html  css  js  c++  java
  • python中初级装饰器总结

    打印 args 与 *args 的区别

    1 #打印时区别
    2 def outer(*args, **kwargs):
    3     print(args)         #输出结果:(1, 2, 3, 4)
    4     print(*args)        #输出结果:1 2 3 4
    5 
    6 outer(1,2,3,4)
     1 #函数调用时区别
     2 def outer(*args, **kwargs):
     3     print(args)
     4     print(*args)        #也是调用函数,调用的是print函数
     5 
     6 outer([1,2,3,4])        #输出结果:([1, 2, 3, 4],)
     7                         #          [1, 2, 3, 4]
     8 
     9 outer(*[1,2,3,4])        #输出结果:(1, 2, 3, 4)
    10                         #           1 2 3 4
    11                         #等价于outer(1,2,3,4),以及outer(*(1,2,3,4))

    规律

     1 def outer(*args, **kwargs):
     2     print(args)
     3     print(*args)        #也是调用函数,调用的是print函数
     4     def inner(*args):
     5         print('inner:',args)
     6     inner(*args)
     7 
     8 outer(1,2,3,4)            #输出结果:(1, 2, 3, 4)
     9 #                         #           1 2 3 4
    10 #                         #           inner: (1, 2, 3, 4)    在被传参时聚合

    总体

    def wrapper(func):
        def inner(*args,**kwargs):
            print('在被装饰的函数执行之前做的事')
            ret = func(*args,**kwargs)
            print('在被装饰的函数执行之后做的事')
            return ret
        return inner
    
    @wrapper
    def func(day):
        print('python目前是排名第{}的语言'.format(day))
        return '所以我们一定要坚持学习python'
    
    ret = func(4)
    print(ret)
  • 相关阅读:
    gorm 更新数据时,0值会被忽略
    xshell评估过期解决办法
    安装zoom
    aria2 加速百度网盘下载
    ubuntu17.10 安装firefox的flash
    c++ 回调函数使用
    ubuntu17 安装中文输入法
    ubuntu python3.6 找不到_sqlite3
    linux 获取CPU个数
    centos7 yum与Python3冲突
  • 原文地址:https://www.cnblogs.com/rcat/p/9333509.html
Copyright © 2011-2022 走看看