import abcclass FormalParserInterface(metaclass=abc.ABCMeta):@classmethoddef __subclasshook__(cls, subclass):return (hasattr(subclass, 'load_data_source') andcallable(subclass.load_data_source) andhasattr(subclass, 'extract_text') andcallable(subclass.extract_text) orNotImplemented)@abc.abstractmethoddef load_data_source(self, path: str, file_name: str):"""Load in the data set"""raise NotImplementedError@abc.abstractmethoddef extract_text(self, full_file_path: str):"""Extract text from the data set"""raise NotImplementedErrorclass PdfParserNew(FormalParserInterface):"""Extract text from a PDF."""def load_data_source(self, path: str, file_name: str) -> str:"""Overrides FormalParserInterface.load_data_source()"""print("i am pdfparser")passdef extract_text(self, full_file_path: str) -> dict:"""Overrides FormalParserInterface.extract_text()"""passclass EmlParserNew(FormalParserInterface):"""Extract text from an email."""def load_data_source(self, path: str, file_name: str) -> str:"""Overrides FormalParserInterface.load_data_source()"""print("i amd eml parser")passdef extract_text(self, full_file_path: str) -> dict:"""A method defined only in EmlParser.Does not override FormalParserInterface.extract_text()"""passmy_pdf_parser = PdfParserNew()my_eml_parser = EmlParserNew()parser_list = [my_pdf_parser, my_eml_parser]for each_parser in parser_list:each_parser.load_data_source("", "")
参考资料
https://realpython.com/python-interface/#using-abstract-method-declaration
