如何快速理解python裝飾器

快速理解

  • 裝飾器,從名字能夠大概看出,其做用能夠歸納爲: 加強(擴展)函數功能。
  • 裝飾器本質上就是: 以函數做爲參數,能返回包含調用該參數函數及其餘功能的新函數的一種函數。
  • 裝飾器經過在須要被裝飾的函數的定義前一行添加@decorator_name的方式使用

舉例說明

源函數

def hello():
    print("hello world!!!")

使用裝飾器擴展hello()功能而不直接修改其定義

def log(func):
    """print function name before it's called"""
    def wrapper(*args, **kw):  # 閉包,實現裝飾器的基礎
        print('call %s():\n' % func.__name__, end="    ")
        return func(*args, **kw)  # 傳遞給wrapper的參數最後傳遞給了func
    return wrapper

@log
def hello():
    print("hello world!!!")

hello()

輸出:python

call hello():
    hello world!!!

將@log 放到hello()定義前一行,至關於執行如下過程

hello = log(hello)  # 此調用的執行效果等效於  log.func = hello, hello = log.wrapper

經過 @property 裝飾器驗證是否能夠使用上述其等效方法替換正常修飾器的使用

class Student(object):
    # @property  # 做用是把類方法轉換成類屬性
    # def score(self):
    #     return self._score

    # 替換 @property的效果
    def score(self):
        return self._score
    score = property(score)

    @score.setter
    def score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer!')
        if value < 0 or value > 100:
            raise ValueError('score must between 0 ~ 100!')
        self._score = value

a = Student()
a.score = 60
a.score

輸出:閉包

60
相關文章
相關標籤/搜索