@abstractmethod抽象方法的使用

194 阅读1分钟

前置条件

父类必须继承自abc.ABC

作用

类似于JAVA中的接口,子类必须实现父类的接口,否则无法进行实例化

关于前置条件

看了很对关于abstractmethod的介绍,都说要继承自ABC,但是没有文章有提到不继承会怎样,是直接报错?还是子类实例化报错?所以我个人手动进行了一些测试,测试结果表明,如果父类不继承ABC,那么@abstractmethod的装饰将没有任何的作用,测试的代码如下:

from abc import ABC, abstractmethod

class Father:
    @abstractmethod
    def run(self):
        """子类必须实现这个方法"""

class Son(Father):
    """
        此时我的子类中并没有重写run方法
    """
    def __repr__(self):
        return f"{self.__class__}"

S = Son()
print(S)  # <class '__main__.Son'>  执行了__repr__方法

此时,我的子类实例正常初始化,且子类中的方法也能正常运行,所以通过这个测试表明了,如果父类没有继承ABC,那么@abstractmethod的装饰将没有意义,所以在使用abstractmethod做装饰器时,该类要继承自ABC类

abstractmethod的作用

from abc import ABC, abstractmethod

class Father(ABC):
    @abstractmethod
    def run(self):
        """子类必须实现这个方法"""

class Son(Father):
    """
        此时我的子类中并没有重写run方法
    """
    def __repr__(self):
        return f"{self.__class__}"
    # def run(self):
    #     print("hello")

S = Son()  # TypeError: Can't instantiate abstract class Son with abstract methods run
print(S)

如果类继承于ABC或者ABCMeta,某个方法被abstractmethod装饰时,那么该类的子类必须实现这个方法,否则无法实现实例化。