抽象类
什么是抽象类
抽象类是一种特殊的类,抽象类中只有抽象方法(没有实现功能),所以只能被继承,不能被实例化,其子类必须实现抽象方法。python也有抽象类的概念,只是需要借助模块实现。
import abc
class Animal(metaclass=abc.ABCMeta):
# name = 'abstractclass'
@abc.abstractmethod
def active(self):
pass
@abc.abstractmethod
def sleep(self):
pass
class Icatchmouse():
def catchmouse(self):
pass
class Cat(Animal,Icatchmouse):
def __init__(self, name):
self.name = name
def active(self):
print('喵~')
def sleep(self):
print('咪咪睡觉了')
def catchmouse(self):
print(self.name+'捕到老鼠了')
class BSCat(Cat,Icatchmouse):
def __init__(self, name):
self.name = name+'bs'
def active(self):
print('bs喵~')
def sleep(self):
print('bs咪咪睡觉了')
def catchmouse(self):
print(self.name+'bs捕到老鼠了')
class Dog(Animal,Icatchmouse):
def __init__(self, name, age):
self.name = name
self.age = age
def active(self):
print('汪汪')
def sleep(self):
print('狗狗睡觉')
if __name__ == '__main__':
cat = BSCat('咪咪')
cat.active()
cat.sleep()
cat.catchmouse()
dog = Dog('旺财', 6)
dog.active()
dog.sleep()
dog.catchmouse()
网友评论