Python之抽象类、抽象方法

时间:2021-11-27 23:33:53

抽象类中只能有抽象方法,子类继承抽象类时,不能通过实例化使用其抽象方法,必须实现该方法。

Python2

class CopyBase(object):
def save(self):
raise NotImplementedError class CopyPaper(CopyBase):
def __init__(self):
pass def save(self):
print("copy paper") class CopyQuestion(CopyBase):
def __init__(self):
pass copy_paper = CopyPaper()
copy_paper.save()
copy_question = CopyQuestion()
copy_question.save() result:
copy paper
Traceback (most recent call last):
copy_question.save()
raise NotImplementedError
NotImplementedError

这里以NotImplementedError的形式实现了抽象类和抽象方法,如果子类不实现该方法会抛出异常

Python3

在Python3中引入了abc模块,通过@abc.abstractmethod可以更加简洁地使用抽象类,抽象方法。

import abc

class CopyBase(metaclass=abc.ABCMeta):
@abc.abstractmethod
def save(self):
pass class CopyPaper(CopyBase):
def __init__(self):
pass def save(self):
print("copy paper") class CopyQuestion(CopyBase):
def __init__(self):
pass copy_paper = CopyPaper()
copy_paper.save()
copy_question = CopyQuestion()
copy_question.save() result:
copy paper
Traceback (most recent call last):
copy_question = CopyQuestion()
TypeError: Can't instantiate abstract class CopyQuestion with abstract methods save

从abc模块引入类abstractmethod和类ABCMeta,自定义的CopyBase类继承抽象类ABCMeta,在类CopyBase中定义save方法,

添加装饰器abcstractmethod,CopyPaper类和CopyQuestion继承CopyBase类,分别实例化CopyPaper和CopyQuestion,

CopyQuestion类没有实现save方法,因此会抛出异常。