zoukankan      html  css  js  c++  java
  • python进阶日记(装饰器的用法)

    修饰器用法:

    import time
    
    def decorate(func):
        def wrapper():
            print("正在校验")
            time.sleep(2)
            print("校验完成")
            func()
    
        return wrapper
    
    '''在你定义这个fun1时其实就已经完成了2步:
    1.把函数传到decorate中 
    2.fun1就等于返回的wrapper函数 
    这个过程运行完你的fun1就修饰完成了,之后就直接运行fun1即可
    '''
    @decorate
    def fun1():
        print(1)
    
    fun1()
    print(fun1)

     多参数的情况:

    import time
    
    def decorate(func):
        print('start')  #只要你定义了装饰器,decorate中除了wrapper外的都会顺序执行
        def wrapper(*args,**kwargs):   #加这两个东西就能随便传任意多的参数了
            print("正在校验")
            time.sleep(2)
            print("校验完成")
            func(*args,**kwargs)
    
        print('end')
        return wrapper
    
    @decorate
    def fun1(students):
        for stu in students:
            print(stu)
    list1 = ['a','b','c']
    #fun1(list1)

    多重装饰器:

    import time
    
    def decorate1(func):
        def wrapper(*args,**kwargs):
            print("正在校验")
            time.sleep(2)
            print("校验完成")
            func(*args,**kwargs)
    
        return wrapper
    
    
    def decorate2(func):
        def wrapper(*args, **kwargs):
            print("正在加载")
            time.sleep(2)
            print("加载完成")
            func(*args, **kwargs)
    
        return wrapper
    
    @decorate2       
    @decorate1     #2个装饰器,先由1装饰原函数,然后由2装饰整体
    def fun1(students):
        for stu in students:
            print(stu)
    list1 = ['a','b','c']
    fun1(list1)

    运行结果:

    -----------------------------------

    正在加载
    加载完成
    正在校验
    校验完成
    a
    b
    c

    ------------------------------------

  • 相关阅读:
    LeetCode 230. Kth Smallest Element in a BST
    LeetCode 114. Flatten Binary Tree to Linked List
    LeetCode 222. Count Complete Tree Nodes
    LeetCode 129. Sum Root to Leaf Numbers
    LeetCode 113. Path Sum II
    LeetCode 257. Binary Tree Paths
    Java Convert String & Int
    Java Annotations
    LeetCode 236. Lowest Common Ancestor of a Binary Tree
    LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
  • 原文地址:https://www.cnblogs.com/cunyusup/p/12411065.html
Copyright © 2011-2022 走看看