zoukankan      html  css  js  c++  java
  • python中的装饰器

    装饰器的作用:给原有的函数添加新的功能但是不改变原有函数的代码

    假设我们有如下的代码,其中hello函数可以打印“Hello”

    1 def hello():
    2     print('hello')

    但是现在我们需要对hello函数添加新的功能,使其可以同时打印‘goodBye’,简单的我们可以使用下面的代码完成

    1 def hello():
    2     print('hello')
    3     print('goodBye')

    或者是这样的

    def goodBye():
         print("goodBye")
    
    def hello():
         goodBye()
         print("hello")

    但是这样的话代码很麻烦,同时当我们需要撤销新加的功能的时候还需要修改源代码,这时就有了装饰器的写法

    def goodBye(f):
        def f2():
            print("goodBye")
            return f()
        return f2
    
    
    @goodBye
    def hello():
        print("hello")
    
    hello()

    上面的代码等价与:

    def goodBye(f):
         def f2():
              print("goodBye")
              return f()
         return f2
    
    def hello():
         print("hello")
    
    hello = goodBye(hello)
    hello()
    知之为知之,不知为不知
  • 相关阅读:
    游标、锁
    树形背包浅谈
    金字塔
    Codeforces Round #652 (Div. 2) 题解
    NOI1999 棋盘分割
    NEERC2002 Folding
    HDU4283 You Are the One
    Codeforces Round #646 (Div. 2) 题解
    洛谷 P1679 神奇的四次方数
    UVA12563 劲歌金曲
  • 原文地址:https://www.cnblogs.com/bevishe/p/10972638.html
Copyright © 2011-2022 走看看