为啥要定义抽象基类,意义何在

你想定义一个接口或抽象类,并且通过执行类型检查来确保子类实现了某些特定的方法

 

运用 abc 模块可以轻松的实现 抽象基类

Python
import abc from abc import ABCMeta,abstractmethod class Http_Base(metaclass=ABCMeta): @abstractmethod def get(self): pass @abstractmethod def set(self,key,velue): pass
1
2
3
4
5
6
7
8
9
10
11
import abc
from abc import ABCMeta , abstractmethod
 
class Http_Base ( metaclass = ABCMeta ) :
     @ abstractmethod
     def get ( self ) :
         pass
 
     @ abstractmethod
     def set ( self , key , velue ) :
         pass

抽象类的一个特点是它不能直接被实例化,比如你想像下面这样做是不行的:

Python
Http_Base() TypeError: Can't instantiate abstract class Http_Base with abstract methods get, set
1
2
Http_Base ( )
TypeError : Can' t instantiate abstract class Http_Base with abstract methods get , set

抽象类的目的就是让别的类继承它并实现特定的抽象方法:

 

Python
class Http(Http_Base): def get(self): pass def set(self,key,velue): pass
1
2
3
4
5
6
class Http ( Http_Base ) :
 
     def get ( self ) :
         pass
     def set ( self , key , velue ) :
         pass

 

全部代码

Python
#需要设计一个抽象基类, 指定子类必须实现某些方法 import abc from abc import ABCMeta,abstractmethod class Http_Base(metaclass=ABCMeta): @abstractmethod def get(self): pass @abstractmethod def set(self,key,velue): pass class Http(Http_Base): def get(self): pass def set(self,key,velue): pass http = Http()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#需要设计一个抽象基类, 指定子类必须实现某些方法
 
import abc
from abc import ABCMeta , abstractmethod
 
class Http_Base ( metaclass = ABCMeta ) :
     @ abstractmethod
     def get ( self ) :
         pass
 
     @ abstractmethod
     def set ( self , key , velue ) :
         pass
 
 
 
class Http ( Http_Base ) :
 
     def get ( self ) :
         pass
     def set ( self , key , velue ) :
         pass
 
 
http = Http ( )

 

 

 

 

 




  • zeropython 微信公众号 5868037 QQ号 5868037@qq.com QQ邮箱
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值