python之抽象基类

抽象基类特点
1.不能够实例化
2.在这个基础的类中设定一些抽象的方法,所有继承这个抽象基类的类必须覆盖这个抽象基类里面的方法
思考

既然python中有鸭子类型,为什么还要使用抽象基类?
一是我们在某些情况下希望判定某个对象的类型:

from collections.abc import Sized
class Company:
    def __init__(self, empo):
        self.empo = empo
    def __len__(self):
        return len(self.empo)

com = Company([1,3,4])
hasAttr(com,'__len__')    // true    如果没有抽象基类,就必须用hasAttr这个方法
print(isinstance(com, Sized))  // true  有了抽象基类之后,可以直接用isinstance判断

二是我们要强制某个子类必须实现某些方法

原文地址:https://www.cnblogs.com/raind/p/10111082.html