@abstractmethod
a class with an abstract method cannot be instantiated (that is, we cannot create an instance by calling it) unless all of its abstract methods have been defined in subclasses. Although this requires more code and extra knowledge, the potential advantage of this approach is that errors for missing methods are issued when we attempt to make an instance of the class, not later when we try to call a missing method. This feature may also be used to define an expected interface, automatically verified in client classes.
在父类中使用@abstractmethod抽象类
子类中必须明确定义这个abstract method才能实例化,否则会报错。
使用@abstractmethod的优点是,避免子类在编程过程中漏掉必要的method。
class A(object):
@abstractmethod
def b(self):
raise NotImplementedError
class B(A):
def b(self):
print("在子类中不重写我会报错")
本文深入探讨了Python中抽象类的概念及@abstractmethod装饰器的使用。解释了如何通过定义抽象方法确保子类实现特定的方法,从而避免编程过程中的遗漏,并在尝试实例化未完全实现的子类时提前发现错误。
545

被折叠的 条评论
为什么被折叠?



