首頁  >  文章  >  後端開發  >  如何在 Python 中裝飾一個類別?

如何在 Python 中裝飾一個類別?

王林
王林轉載
2023-05-26 14:43:061379瀏覽

如何在 Python 中装饰一个类?

它使用額外的 Python 語句修改舊物件並傳回相同的參考。

例如,考慮下面的類,它有兩個方法:__init__和 display。 __init__方法在顯示輸出名稱時初始化名稱變數:

class Student:
def __init__(self, name):
self.name = name
def display(self):
print('Name:', self.name)

要在 Python 中裝飾這個類,我們可以向該類別添加新方法或修改現有方法,或者兩者都做。

此外,在 Python 中有兩種方法可以做到這一點,要么使用函數裝飾器,要么使用類別裝飾器。

讓我們一個一個看下例子。

使用函數裝飾器裝飾類別

要使用函數裝飾器來裝飾類,接受類別作為參數,修改其程式碼並在最後傳回類別。

def mydecorator(student):
#define a new display method
def newdisplay(self):
print('Name: ', self.name)
print('Subject: Programming')
#replace the display with newdisplay
student.display = newdisplay

#return the modified student
return student
@mydecorator
class Student:
def __init__(self, name):
self.name = name
def display(self):
print('Name:', self.name)
obj = Student('Pencil Programmer')
obj.display()
'''
Name: Pencil Programmer
Subject: Programming
'''

如果類別中不存在 display 方法,則 newdisplay 將作為 display 方法新增至類別。

  •  由於類別的引用在裝飾器函數中是可用的,我們除了修改現有方法外,還可以為類別添加新的屬性和方法

使用類別裝飾器裝飾類別

要使用類別裝飾器裝飾類,接受類別的引用作為參數(在裝飾器的__init__方法中),在__call__方法中修改其程式碼,最後傳回修改後的類別的實例。

class Mydecorator:
#accept the class as argument
def __init__(self, student):
self.student = student

#accept the class's __init__ method arguments
def __call__(self, name):
#define a new display method
def newdisplay(self):
print('Name: ', self.name)
print('Subject: Python')

#replace display with newdisplay
self.student.display = newdisplay

#return the instance of the class
obj = self.student(name)
return obj
@Mydecorator
class Student:
def __init__(self, name):
self.name = name

def display(self):
print('Name: ', self.name)
obj = Student('Pencil Programmer')
obj.display()
'''
Name: Pencil Programmer
Subject: Python
'''

這裡唯一的差異是我們回傳的是物件的參考而不是類別參考。

原文:https://www.php.cn/link/137ffea9336f8b47a66439fc34e981ee

#

以上是如何在 Python 中裝飾一個類別?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:51cto.com。如有侵權,請聯絡admin@php.cn刪除