Python本身不具有抽象类,通过导入abc模块可以另一抽象类和抽象方法。
from abc import abstractmethod, ABCMeta
class Base(metaclass=ABCMeta):
@abstractmethod
def method1(self):
pass
def method2(self):
print('This is a general method.')
class children(Base):
def method1(self):
print('This is an abstractmethod.')
child = children()
child.method1() # This is an abstractmethod.
child.method2() # This is a general method.
抽象类必须通过ABCMeta元类来定义;
抽象类不能直接实例化,否则会抛出异常:TypeError: Can’t instantiate abstract class [className] with abstract methods [methodNames];
抽象方法必须在子类中重写来实现,否则会抛出异常:TypeError: Can’t instantiate abstract class [className] with abstract methods [methodNames];