Python - 裝飾器



在 Python 中,裝飾器是一個函式,它接收另一個函式作為引數。被裝飾的函式就是作為引數傳入的函式。裝飾器可以擴充套件引數函式的行為,而無需實際修改它。

在本章中,我們將學習如何使用 Python 裝飾器。

定義函式裝飾器

Python 中的函式是一等公民。這意味著它可以像其他資料型別(如數字、字串或列表等)一樣作為引數傳遞給另一個函式。也可以在一個函式內部定義另一個函式。這樣的函式稱為巢狀函式。此外,函式也可以返回其他函式。

裝飾器函式的典型定義如下:

def decorator(arg_function): #arg_function to be decorated
   def nested_function():
      #this wraps the arg_function and extends its behaviour
      #call arg_function
      arg_function()
   return nested_function

這是一個普通的 Python 函式:

def function():
   print ("hello")

現在可以透過將其傳遞給裝飾器來裝飾此函式以擴充套件其行為:

function=decorator(function)

如果現在執行此函式,則將顯示由裝飾器擴充套件的輸出。

Python 裝飾器的示例

練習以下示例以理解 Python 裝飾器的概念:

示例 1

以下程式碼是裝飾器的簡單示例:

def my_function(x):
   print("The number is=",x)

def my_decorator(some_function,num):
   def wrapper(num):
      print("Inside wrapper to check odd/even")
      if num%2 == 0:
         ret= "Even"
      else:
         ret= "Odd!"
      some_function(num)
      return ret
   print ("wrapper function is called")
   return wrapper

no=10
my_function = my_decorator(my_function, no)
print ("It is ",my_function(no))

my_function() 只打印接收到的數字。但是,透過將其傳遞給 my_decorator,它的行為被修改了。內部函式接收數字並返回它是奇數還是偶數。上述程式碼的輸出為:

wrapper function is called
Inside wrapper to check odd/even
The number is= 10
It is Even

示例 2

裝飾函式的一種優雅方式是在其定義之前加上 @ 符號和裝飾器的名稱。上面的例子使用這種表示法重寫:

def my_decorator(some_function):
   def wrapper(num):
      print("Inside wrapper to check odd/even")
      if num%2 == 0:
         ret= "Even"
      else:
         ret= "Odd!"
      some_function(num)
      return ret
   print ("wrapper function is called")
   return wrapper

@my_decorator
def my_function(x):
   print("The number is=",x)
no=10
print ("It is ",my_function(no))

Python 的標準庫定義了以下內建裝飾器:

@classmethod 裝飾器

classmethod 是一個內建函式。它將方法轉換為類方法。類方法與例項方法不同。在類中定義的例項方法由其物件呼叫。該方法接收由 self 引用的隱式物件。另一方面,類方法隱式地接收類本身作為第一個引數。

語法

為了宣告類方法,使用以下裝飾器表示法:

class Myclass:
   @classmethod
   def mymethod(cls):
   #....

@classmethod 形式是前面描述的函式裝飾器形式。mymethod 接收對類的引用。它可以由類及其物件呼叫。這意味著 Myclass.mymethod 和 Myclass().mymethod 都是有效的呼叫。

@classmethod 裝飾器的示例

讓我們透過以下示例來了解類方法的行為:

class counter:
   count=0
   def __init__(self):
      print ("init called by ", self)
      counter.count=counter.count+1
      print ("count=",counter.count)
   @classmethod
   def showcount(cls):
      print ("called by ",cls)
      print ("count=",cls.count)

c1=counter()
c2=counter()
print ("class method called by object")
c1.showcount()
print ("class method called by class")
counter.showcount()

在類定義中,count 是一個類屬性。__init__() 方法是建構函式,顯然是一個例項方法,因為它接收 self 作為物件引用。宣告的每個物件都會呼叫此方法並將 count 加 1。

@classmethod 裝飾器將 showcount() 方法轉換為類方法,即使它由其物件呼叫,它也接收對類的引用作為引數。即使 c1 物件呼叫 showcount,它也會顯示計數器類的引用。

它將顯示以下輸出

init called by <__main__.counter object at 0x000001D32DB4F0F0>
count= 1
init called by <__main__.counter object at 0x000001D32DAC8710>
count= 2
class method called by object
called by <class '__main__.counter'>
count= 2
class method called by class
called by <class '__main__.counter'>

@staticmethod 裝飾器

staticmethod也是Python標準庫中的內建函式。它將一個方法轉換為靜態方法。無論靜態方法是由類的例項還是類本身呼叫,它都不會接收任何引用引數。在類中宣告靜態方法使用以下表示法:

語法

class Myclass:
@staticmethod
def mymethod():
#....

儘管Myclass.mymethod和Myclass().mymethod都是有效的呼叫,但靜態方法都不會接收任何引用。

@staticmethod裝飾器的示例

計數器類被修改如下:

class counter:
   count=0
   def __init__(self):
      print ("init called by ", self)
      counter.count=counter.count+1
      print ("count=",counter.count)
   @staticmethod
   def showcount():
      print ("count=",counter.count)

c1=counter()
c2=counter()
print ("class method called by object")
c1.showcount()
print ("class method called by class")
counter.showcount()

和以前一樣,類屬性count在__init__()方法中每個物件的宣告時都會遞增。但是,由於mymethod()是一個靜態方法,它既不接收self引數也不接收cls引數。因此,類屬性count的值需要顯式引用counter才能顯示。

以上程式碼的輸出如下:

init called by <__main__.counter object at 0x000002512EDCF0B8>
count= 1
init called by <__main__.counter object at 0x000002512ED48668>
count= 2
class method called by object
count= 2
class method called by class
count= 2

@property裝飾器

Python的property()內建函式是訪問類例項變數的介面。@property裝飾器將例項方法轉換為具有相同名稱的只讀屬性的“getter”,並將屬性的文件字串設定為“獲取例項變數的當前值”。

可以使用以下三個裝飾器來定義屬性:

  • @property − 將方法宣告為屬性。

  • @.setter: − 指定為屬性設定值的setter方法。

  • @.deleter − 指定作為刪除屬性的刪除方法。

property()函式返回的屬性物件具有getter、setter和deleter方法。

property(fget=None, fset=None, fdel=None, doc=None)

fget引數是getter方法,fset是setter方法。它可以選擇具有fdel作為刪除物件的方法,doc是文件字串。

語法

property()物件的setter和getter也可以使用以下語法賦值:

speed = property()
speed=speed.getter(speed, get_speed)
speed=speed.setter(speed, set_speed)

其中get_speed()和set_speeds()是檢索和設定Car類中例項變數speed值的例項方法。

以上語句可以用@property裝飾器實現。使用該裝飾器,car類被改寫為:

@property裝飾器的示例

class car:
   def __init__(self, speed=40):
      self._speed=speed
      return
   @property
   def speed(self):
      return self._speed
   @speed.setter
   def speed(self, speed):
      if speed<0 or speed>100:
         print ("speed limit 0 to 100")
         return
      self._speed=speed
      return

c1=car()
print (c1.speed) #calls getter
c1.speed=60 #calls setter

屬性裝飾器是一種非常方便且推薦的處理例項屬性的方法。

廣告