自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

如何在 Python 中裝飾一個類?

開發(fā) 后端
在本篇中,我們將學(xué)習(xí)使用函數(shù)和類裝飾器在 Python 中裝飾一個類,Python 中的裝飾器是修改現(xiàn)有函數(shù)或類的任何可調(diào)用對象。

它使用額外的 Python 語句修改舊對象并返回相同的引用。

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

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

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

此外,在 Python 中有兩種方法可以做到這一點(diǎn),要么使用函數(shù)裝飾器,要么使用類裝飾器。

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

使用函數(shù)裝飾器裝飾類

要使用函數(shù)裝飾器來裝飾類,接受類作為參數(shù),修改其代碼并在最后返回類。

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 方法添加到類中。

  •  由于類的引用在裝飾器函數(shù)中是可用的,我們除了修改現(xiàn)有方法外,還可以為類添加新的屬性和方法

使用類裝飾器裝飾類

要使用類裝飾器裝飾類,接受類的引用作為參數(shù)(在裝飾器的__init__方法中),在 __call__方法中修改其代碼,最后返回修改后的類的實(shí)例。

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
'''

這里唯一的區(qū)別是我們返回的是對象的引用而不是類引用。

原文:??https://pencilprogrammer.com/decorate-python-class/??

責(zé)任編輯:龐桂玉 來源: python運(yùn)維技術(shù)
相關(guān)推薦

2021-02-14 13:38:17

Python開發(fā)函數(shù)

2024-04-18 10:23:35

裝飾器Python

2016-12-07 17:45:44

Linux文件

2022-08-14 08:29:21

npmNode

2024-04-11 08:30:05

JavaScript數(shù)組函數(shù)

2012-03-14 11:08:32

JavaJLayer

2025-04-14 08:35:00

Python類裝飾器裝飾器

2019-05-21 13:55:22

Python編程語言游戲

2021-11-01 12:13:53

Linux僵尸進(jìn)程

2021-09-14 12:34:33

LinuxLinux終端

2024-11-04 15:30:43

Python裝飾器函數(shù)

2019-09-10 09:12:54

2011-04-01 09:49:54

Python

2021-07-02 07:18:19

Goresults通道類型

2016-07-18 10:51:19

操作系統(tǒng)LinuxWindows

2019-08-12 09:55:10

GitHub項目終端

2021-09-02 08:02:50

深度學(xué)習(xí)Kubernetes集群管理

2021-05-28 18:12:51

C++設(shè)計

2021-11-15 10:35:46

Python線程代碼
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號