1.一般来说,通过继承可以获得父类的属性,还可以通过重载修改其方法。
2.装饰模式可以不以继承的方式而动态地修改类的方法。
3.装饰模式可以不以继承的方式而返回一个被修改的类。
4.基本实现
程序演示如下:
例一:
13_eg1.py
class BeDeco:
def be_edit_fun(self):
print('Source fun.')
def be_keep_fun(self):
print('Keep fun.')
class Decorater:
def __init__(self,dec):
self._dec = dec()
def be_edit_fun(self):
print('Start...')
self._dec.be_edit_fun()
def be_keep_fun(self):
self._dec.be_keep_fun()
if __name__ == '__main__':
bd = BeDeco()
bd.be_edit_fun()
bd.be_keep_fun()
dr = Decorater(BeDeco)
dr.be_edit_fun()
dr.be_keep_fun()
程序的运行结果为:
例二:
13_eg2.py
class Water:
def __init__(self):
self.name = 'Water'
def show(self):
print(self.name)
class Deco:
def show(self):
print(self.name)
class Sugar(Deco):
def __init__(self,water):
self.name = 'Sugar'
self.water = water
def show(self):
print(self.name)
print(self.water.name)
class Salt(Deco):
def __init__(self,water):
self.name = 'Salt'
self.water = water
def show(self):
print(self.name)
print(self.water.name)
if __name__ == '__main__':
w = Water()
s = Sugar(w)
s.show()
s = Salt(w)
s.show()
程序的运行结果为:
5.类装饰器
程序演示如下:
13_eg3.py
def deco(a_class):
class NewClass:
def __init__(self,age,color):
self.wrapped = a_class(age)
self.color = color
def display(self):
print(self.color)
print(self.wrapped.age)
return NewClass
@deco
class Cat:
def __init__(self,age):
self.age = age
def display(self):
print(self.age)
if __name__ == '__main__':
c = Cat(12,'black')
c. display()
程序的运行结果为: