你想定义一个接口或抽象类,并且通过执行类型检查来确保子类实现了某些特定的方法
运用 abc 模块可以轻松的实现 抽象基类
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
|
抽象类的一个特点是它不能直接被实例化,比如你想像下面这样做是不行的:
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
|
抽象类的目的就是让别的类继承它并实现特定的抽象方法:
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
|
全部代码
#需要设计一个抽象基类, 指定子类必须实现某些方法 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
(
)
|