python中的抽象类

版权声明:https://blog.csdn.net/study_in https://blog.csdn.net/study_in/article/details/85838909

@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("在子类中不重写我会报错")

猜你喜欢

转载自blog.csdn.net/study_in/article/details/85838909
0条评论
添加一条新回复