abc模块-抽象基类

      初次见到这个模块,一脸懵逼,怎么还有这种命名方式,后来才了解,原来只是简称,全称是abstract base classes,中文名抽象基类。有点类似于java中的抽象接口的概念。我认为它的主要作用是就是我们常说的继承和多态,抽象基类中可以选择定义一组方法而不实现,由其子类去继承并实现。其子类包含两种类型,一是继承类,继承父类的方法和属性,一是虚拟子类,也叫注册类,它不会从父类继承任何方法和属性。

import abc


class AbstractFatherClass(metaclass=abc.ABCMeta):
@abc.abstractmethod
def func_1(self):
raise NotImplementedError

@classmethod
@abc.abstractmethod
def func_2(cls):
raise NotImplementedError

@staticmethod
@abc.abstractmethod
def func_3():
raise NotImplementedError

@classmethod
def func_4(cls):
print("函数4")


class ChildClass(AbstractFatherClass):
def func_1(self):
print("函数1")

@classmethod
def func_2(cls):
print("函数2")

@staticmethod
def func_3():
print("函数3")


if __name__ == '__main__':
child_class = ChildClass()
child_class.func_1()
child_class.func_2()
child_class.func_4()

ChildClass.func_3()

猜你喜欢

转载自www.cnblogs.com/luopan/p/10104774.html
今日推荐