#!/usr/bin/python3
import abc
#这里定义了一个抽象基类(ABC),继承abc.ABC
class animal(abc.ABC):
@abc.abstractmethod
def getName(self):
"""获取动物名称"""
#定义一个子类
class Cat(animal):
def getName(self):
return '猫,Hellokitty'
#定义了子类,但是没有重定义虚函数getName.
#import时不会报错,运行时报错,即定义对象时报错,如下所示。
class Dog(animal):
def __init__(self):
print('汪汪汪...')
if __name__=='__main__':
c=Cat()
print(isinstance(c,animal))
d=Dog()#此处报错--->TypeError: Can't instantiate abstract class Dog with abstract methods getName
---------------
扫一扫,关注我们