抽象类、归一化设计、Super()方法
抽象类
-
抽象类是一个开发的规范,约束它的所有子类必须实现一些和它同名的方法
-
方式一:好处不用依赖包
class Payment: #Payment就是抽象类 def pay(self,money): raise NotImplemented('请在子类中写同名pay方法') class Ailpay(Payment): def __init__(self,name): self.name=name def pay(self,money): dic={'aname':self.name,'price':money} print(f'{self.name}通过支付宝支付了{money}元') class WeChat(Payment): def __init__(self,name): self.name=name def pay(self,money): dic={'aname':self.name,'money':money} print(f'{self.name}通过微信支付了{money}元') class Apple(Payment): def __init__(self,name): self.name=name def pay(self,money): dic={'aname':self.name,'money':money} print(f'{self.name}通过苹果支付了{money}元') #归一化设计 def pays(name,price,kind): if kind=='WeChat': obj=WeChat(name) elif kind=='Ailpay': obj=Ailpay(name) elif kind=='Apple': obj=Apple(name) obj.pay(price) pays('xiaotong',100,'WeChat') pays('wangminmin',200,'Ailpay') pays('baoli',300,'Apple')
-
方式二 (使用abc包) 好处如果子类名称不对那么调用类时就报错
from abc import ABCMeta,abstractmethod class Payment(metaclass=ABCMeta): #Payment就是抽象类 @abstractmethod def pay(self,money):pass class Ailpay(Payment): def __init__(self,name): self.name=name def pay(self,money): dic={'aname':self.name,'price':money} print(f'{self.name}通过支付宝支付了{money}元') class WeChat(Payment): def __init__(self,name): self.name=name def pay(self,money): dic={'aname':self.name,'money':money} print(f'{self.name}通过微信支付了{money}元') class Apple(Payment): def __init__(self,name): self.name=name def pay(self,money): dic={'aname':self.name,'money':money} print(f'{self.name}通过苹果支付了{money}元') #归一化设计 def pays(name,price,kind): if kind=='WeChat': obj=WeChat(name) elif kind=='Ailpay': obj=Ailpay(name) elif kind=='Apple': obj=Apple(name) obj.pay(price) pays('xiaotong',100,'WeChat') pays('wangminmin',200,'Ailpay') pays('baoli',300,'Apple')
归一化设计
- 把对象作为参数传入函数中,根据对象.方法()调用方法,从而实现不同功能的方法(函数)可以使用相同的方法名(函数名)
Super()方法
-
super()方法只能在新式类中使用(继承自object)
-
super是按照mro顺序来寻找当前类的下一个类的
-
在python2中使用super是要传参数的super(子类类名,self),如果不传则报错,python3中可以不用传。
class A:
def __init__(self):
self.n = 2
def add(self, m):
print('self is {0} @A.add'.format(self.n)) #3
self.n += m #7
print(self.n)
class B(A):
def __init__(self):
self.n = 3
def add(self, m):
print('self is {0} @B.add'.format(self.n)) #2
super().add(m)
self.n += 3 #10
class C(A):
def __init__(self):
self.n = 4
def add(self, m):
print('self is {0} @C.add'.format(self.n))
super().add(m)
self.n += 4
class D(B, C):
def __init__(self):
self.n = 5
def add(self, m):
print('self is {0} @D.add'.format(self.n)) #self.n : 5
super().add(m) #1
self.n += 5 #15
b = B()
b.add(2)
print(type(b))
d = D()
d.add(2)
print(d.n)
# self is 3 @B.add
# self is 3 @A.add
# 5
# <class '__main__.B'>
# self is 5 @D.add
# self is 5 @B.add
# self is 5 @C.add
# self is 5 @A.add
# 7
# 19
# A(O)=[AO]
# B(A)=[BAO]
# C(A)=[CAO]
# D(B,C)=B(A)+C(A)
# D=[BAO]+[CAO]
# DB=[AO]+[CAO]
# DBC=[AO]+[AO]
# DBCA=[O]+[O]
# DBCAO