定义函数作为统一接口:
class Dog:
def __init__(self,name) -> None:
self.name=name
def sound(self):
print(f"{self.name}:汪汪汪!")
class Cat:
def __init__(self,name) -> None:
self.name=name
def sound(self):
print(f"{self.name}:喵喵喵!")
def makeSound(animal_type):
"""调用统一接口"""
animal_type.sound()
d=Dog("alex")
c=Cat("Bob")
makeSound(d)
重写抽象类实例方法作为统一接口:
class Document:
def __init__(self,name) -> None:
self.name=name
def show(self):
raise NotImplementedError("Subclass must implement abstract method")
class Pdf(Document):
def show(self):
print("Show pdf contents!")
class Excel(Document):
def show(self):
print("Show excel contents!")
p=Pdf("10小时学会python面向对象.pdf")
e=Excel("道路数据.doc")
p.show()
e.show()