,[toc]
簡單來說,裝飾器就是用來包裝函式或類的「函式」,它接收乙個物件(函式物件或類物件),並且返回乙個物件(函式物件或類物件)。
用於包裝函式的裝飾器
首先給出一段**,然後我們試著用包裝器來包裝它;
def
squaresum
(a, b):
print("input", a, b)
return a**2 + b**2
defsquarediff
(a, b):
print("input", a, b)
return a**2 - b**2
print(squaresum(4,2))
print(squarediff(4,2))
現在我們來嘗試將上面的**進行包裝;
code1:無引數**示例
#定義乙個裝飾器
defdecorator
(func):
##接收乙個可呼叫物件func
#用來包裝的**段
defhl_func
(a, b):
print("input", a, b)
return func(a, b)
return hl_func #返回乙個可呼叫物件
@decorator #注意這裡,非常重要,等價於decorator(squaresum)
defsquaresum
(a, b):
return a**2 + b**2
@decorator
defsquarediff
(a, b):
return a**2 - b**2
print(squaresum(4,2))
print(squarediff(4,2))
code2:有引數**示例
#新的裝飾器包裝層
defprestring
(pre = ''):
#新的裝飾器的名稱,並且有乙個引數pre
#舊的裝飾器
defdecorator
(func):
defhl_func
(a, b):
print(pre + "input", a, b)
return func(a, b)
return hl_func
return decorator #返回舊的裝飾器的名稱
@prestring('sum +') #注意跟無參的區別
defsquaresum
(a, b):
return a**2 + b**2
@prestring('diff -')
defsquarediff
(a, b):
return a**2 - b**2
print(squaresum(4,2))
print(squarediff(4,2))
其實很簡單,就是在舊的裝飾器外面又包裝了一層,並返回舊的裝飾器;
用於包裝類的裝飾器
接收乙個類物件,並且返回乙個類物件;
def
decorator
(class_name):
class
class_hl:
def__init__
(self, footnum):
self.displaynum = 0
self.type = class_name(footnum) #傳入乙個footnum引數
defdisplay
(self):
self.displaynum += 1;
print("the times of display is: ", self.displaynum)
self.type.display()
return class_hl
@decorator #注意,同樣要帶上這句,不能忘
class
animal:
def__init__
(self, footnum):
self.footnum = footnum
defdisplay
(self):
print("the number of foot is: ", self.footnum)
cat = animal(4) #宣告乙個要傳入裝飾器的類物件,並初始化footnum
for i in range(5):
cat.display()
列印結果:
times
of display is: 1
thenumber
of foot is: 4
thetimes
of display is: 2
thenumber
of foot is: 4
thetimes
of display is: 3
thenumber
of foot is: 4
thetimes
of display is: 4
thenumber
of foot is: 4
thetimes
of display is: 5
thenumber
of foot is: 4
Python 學習筆記 裝飾器
裝飾器也是乙個函式 巢狀 用來裝飾某個函式,來看下面的 import time deftime count func def start time.time func end time.time print this funnction costs end start deftellhi print...
Python學習筆記 裝飾器
裝飾器 概念 是乙個閉包,把乙個函式當做引數返回乙個替代版的函式,本質上就是乙個返回函式的函式 簡單的裝飾器 def func1 print welcome to beijing def outer func def inner print func return inner f是函式func1的加...
Python裝飾器 學習筆記
python中一切皆物件,函式也可以當做引數傳遞 裝飾器接受函式當做引數,新增功能後返回乙個新函式的函式 python中裝飾器使用 import time deflog time func def log args,kwargs begin time.time res func args,kwarg...