欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python 实现装饰器设计模式

程序员文章站 2022-06-30 21:45:07
python 装饰器简单、基本的实现并不复杂。装饰器(Decorators)模式类似于继承,当你需要为某一个对象添加额外的动作、行为时,在不改变类的情况下可以使用装饰器。这篇文就当做一篇水文,本来不想写,因为这个专栏是设计模式的多语言基本实现,不涉及过多内容,为了保证内容完整,所以只能直接塞进来了。首先我们先新建一个人的基类,并且赋予几个属性(名字、性别、头发、衣服等),并且由两个基类,男人和女人:class People(): name = "" sex="" clothes...

python 装饰器简单、基本的实现并不复杂。装饰器(Decorators)模式类似于继承,当你需要为某一个对象添加额外的动作、行为时,在不改变类的情况下可以使用装饰器。这篇文就当做一篇水文,本来不想写,因为这个专栏是设计模式的多语言基本实现,不涉及过多内容,为了保证内容完整,所以只能直接塞进来了。

首先我们先新建一个人的基类,并且赋予几个属性(名字、性别、头发、衣服等),并且由两个基类,男人和女人:

class People():
    name = ""
    sex=""
    clothes = "没穿"
    hair="光头"
    sound_color=""

class Man(People):
    def __init__(self,name):
        self.name=name
        self.sex="男"
 
class Woman(People):
    def __init__(self,name):
        self.name=name
        self.sex="女" 

由于类以及新建,不进行改变,使用装饰器进行行为状态添加,是用装饰器。
新建一个装饰器基类,设置好装饰器方法,gethair 与 getclothes,再写两个类 hairDecorator与 dressedDecorator 继承于 exteriorDecorator,在装饰器 hairDecorator 中使对象长出头发,原有对象中头发的属性值是关头,在 dressedDecorator 中使对象穿上衣服,原有属性为没穿衣服。装饰器类如下:

class exteriorDecorator():#外形装饰基
    def gethair(self):
        pass
    def getclothes(self):
        pass
        
class hairDecorator(exteriorDecorator):#头发装饰
    def __init__(self,people):
        self.people=people
        self.sex="男"
    def gethair(self):
        return str(self.people.name)+" 长出头发"

class dressedDecorator(exteriorDecorator):#外衣装饰
    def __init__(self,people):
        self.people=people
        self.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())

结果如下:
python 实现装饰器设计模式
完整代码如下:

class People():
    name = ""
    sex=""
    clothes = "没穿"
    hair="光头"
    sound_color=""

class Man(People):
    def __init__(self,name):
        self.name=name
        self.sex="男"
 
class Woman(People):
    def __init__(self,name):
        self.name=name
        self.sex="女" 


class exteriorDecorator():#外形装饰基
    def gethair(self):
        pass
    def getclothes(self):
        pass
        
class hairDecorator(exteriorDecorator):#头发装饰
    def __init__(self,people):
        self.people=people
        self.sex="男"
    def gethair(self):
        return str(self.people.name)+" 长出头发"

class dressedDecorator(exteriorDecorator):#外衣装饰
    def __init__(self,people):
        self.people=people
        self.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())

本文地址:https://blog.csdn.net/A757291228/article/details/107100321