日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python 实现装饰器设计模式

發布時間:2023/12/4 python 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python 实现装饰器设计模式 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

python 裝飾器簡單、基本的實現并不復雜。裝飾器(Decorators)模式類似于繼承,當你需要為某一個對象添加額外的動作、行為時,在不改變類的情況下可以使用裝飾器。這篇文就當做一篇水文,本來不想寫,因為這個專欄是設計模式的多語言基本實現,不涉及過多內容,為了保證內容完整,所以只能直接塞進來了。

首先我們先新建一個人的基類,并且賦予幾個屬性(名字、性別、頭發、衣服等),并且由兩個基類,男人和女人:

class People():name = ""sex=""clothes = "沒穿"hair="光頭"sound_color=""class Man(People):def __init__(self,name):self.name=nameself.sex="男"class Woman(People):def __init__(self,name):self.name=nameself.sex="女"

由于類以及新建,不進行改變,使用裝飾器進行行為狀態添加,是用裝飾器。
新建一個裝飾器基類,設置好裝飾器方法,gethair 與 getclothes,再寫兩個類 hairDecorator與 dressedDecorator 繼承于 exteriorDecorator,在裝飾器 hairDecorator 中使對象長出頭發,原有對象中頭發的屬性值是關頭,在 dressedDecorator 中使對象穿上衣服,原有屬性為沒穿衣服。裝飾器類如下:

class exteriorDecorator():#外形裝飾基def gethair(self):passdef getclothes(self):passclass hairDecorator(exteriorDecorator):#頭發裝飾def __init__(self,people):self.people=peopleself.sex="男"def gethair(self):return str(self.people.name)+" 長出頭發"class dressedDecorator(exteriorDecorator):#外衣裝飾def __init__(self,people):self.people=peopleself.sex="男"def getclothes(self):return str(self.people.name)+" 穿上外衣"

以上裝飾器在初始化時傳入了類對象。接下來新建一個對象小明與裝飾器對象:

xiaoming=Man("小明") xiaomingHariD=hairDecorator(xiaoming)

使用hairDecorator 方法裝飾小明的頭發,使用 dressedDecorator 裝飾小明的上衣:

xiaomingHariD=hairDecorator(xiaoming) xiaomingdressedD=dressedDecorator(xiaoming)

最后進行輸出:

print(xiaomingHariD.gethair()) print(xiaomingdressedD.getclothes())

結果如下:

完整代碼如下:

class People():name = ""sex=""clothes = "沒穿"hair="光頭"sound_color=""class Man(People):def __init__(self,name):self.name=nameself.sex="男"class Woman(People):def __init__(self,name):self.name=nameself.sex="女" class exteriorDecorator():#外形裝飾基def gethair(self):passdef getclothes(self):passclass hairDecorator(exteriorDecorator):#頭發裝飾def __init__(self,people):self.people=peopleself.sex="男"def gethair(self):return str(self.people.name)+" 長出頭發"class dressedDecorator(exteriorDecorator):#外衣裝飾def __init__(self,people):self.people=peopleself.sex="男"def getclothes(self):return str(self.people.name)+" 穿上外衣"xiaoming=Man("小明") print(xiaoming.name) xiaomingHariD=hairDecorator(xiaoming) xiaomingdressedD=dressedDecorator(xiaoming) print(xiaomingHariD.gethair()) print(xiaomingdressedD.getclothes())

總結

以上是生活随笔為你收集整理的python 实现装饰器设计模式的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。