java只能继承一个类,但能继承多个接口,接口不能实例化。
python的抽象基类也不能实例化
class Company(object):
def __len__(self):
return 10
company = Company()
# 当使用len()内置函数时,会首先调用__len__方法
print(len(company))
# 检查某个类是否有某种方法
# hasattr()内置函数:用于判断对象是否有某个属性
hasattr(company,"__len__") # 返回True
抽象基类用法1:
判定某个对象的类型——需要用到抽象基类
from collections.abc import Sized print(isinstance(company,Sized))抽象基类用法2: 强制某个子类必须实现某些方法——需要用到抽象基类
例如实现web框架,继承cache(redis,cache,memorycache)
需要设计一个抽象基类,指定子类必须实现某些方法——做框架时要考虑的
class Cachebase():
def get(self, key):
raise NotImplementedError
def set(self, key, value):
raise NotImplementedError
class RedisCache(Cachebase):
pass
redis_cache = RedisCache()
# 在RedisCache中没有改写setget方法,就去调用,会在基类中抛出异常
redis_cache.set()
抽象基类(abc模块)
在python中已经实现了通用的抽象基类collection的abc模块,即collection.abc,可了解python数据结构的接口
模拟实现一个抽象基类:未重写基类的抽象方法时,初始化就报错
import abc # 全局下的abc
class Cachebase1(metaclass=abc.ABCmeta):
@abc.abstractmethod
def get(self, key):
pass
@abc.abstractmethod
def set(self, key, value):
pass
class RedisCache(Cachebase1):
pass
# 这里会报错
redis_cache = RedisCache()
但要注意:抽象基类是很少使用的,抽象基类更像是说明文档!为了说明python中的某些属性,不推荐使用抽象基类!


