https://www.jb51.net/article/87710.htm

像java一样python也可以定义一个抽象类。

在讲抽象类之前,先说下抽象方法的实现。

抽象方法是基类中定义的方法,但却没有任何实现。在java中,可以把方法申明成一个接口。而在python中实现一个抽象方法的简单的方法是:

?
1
2
3
class Sheep(object):
  def get_size(self):
    raise NotImplementedError

任何从Sheep继承下来的子类必须实现get_size方法。否则就会产生一个错误。但这种实现方法有个缺点。定义的子类只有调用那个方法时才会抛错。这里有个简单方法可以在类被实例化后触发它。使用python提供的abc模块。

?
1
2
3
4
5
6
7
import abc
class Sheep(object):
  __metaclass__ = abc.ABCMeta
   
  @abc.absractmethod
  def get_size(self):
    return

这里实例化Sheep类或任意从其继承的子类(未实现get_size)时候都会抛出异常。

因此,通过定义抽象类,可以定义子类的共同method(强制其实现)。

如何使用抽象类

?
1
2
3
4
5
6
7
8
9
10
11
12
import abc
class A(object):
  __metaclass__ = abc.ABCMeta
  @abc.abstractmethod
  def load(self, input):
    return
  @abc.abstractmethod
  def save(self, output, data):
    return

通过ABCMeta元类来创建一个抽象类, 使用abstractmethod装饰器来表明抽象方法

注册具体类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
class B(object):
   
  def load(self, input):
    return input.read()
  def save(self, output, data):
    return output.write(data)
A.register(B)
if __name__ == '__main__':
  print issubclass(B, A)   # print True
  print isinstance(B(), A)  # print True

从抽象类注册一个具体的类

子类化实现

?
1
2
3
4
5
6
7
8
9
10
11
class C(A):
  def load(self, input):
    return input.read()
  def save(self, output, data):
    return output.write(data)
     
if __name__ == '__main__':
  print issubclass(C, A)   # print True
  print isinstance(C(), A)  # print True

可以使用继承抽象类的方法来实现具体类这样可以避免使用register. 但是副作用是可以通过基类找出所有的具体类

?
1
2
3
4
for sc in A.__subclasses__():
  print sc.__name__
# print C

如果使用继承的方式会找出所有的具体类,如果使用register的方式则不会被找出

使用__subclasshook__

使用__subclasshook__后只要具体类定义了与抽象类相同的方法就认为是他的子类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import abc
class A(object):
  __metaclass__ = abc.ABCMeta
  @abc.abstractmethod
  def say(self):
    return 'say yeah'
  @classmethod
  def __subclasshook__(cls, C):
    if cls is A:
      if any("say" in B.__dict__ for B in C.__mro__):
        return True
    return NotTmplementd
class B(object):
  def say(self):
    return 'hello'
print issubclass(B, A)   # True
print isinstance(B(), A)  # True
print B.__dict__      # {'say': <function say at 0x7f...>, ...}
print A.__subclasshook__(B) # True

不完整的实现

?
1
2
3
4
5
6
7
class D(A):
  def save(self, output, data):
    return output.write(data)
if __name__ == '__main__':
  print issubclass(D, A)   # print True
  print isinstance(D(), A)  # raise TypeError

如果构建不完整的具体类会抛出D不能实例化抽象类和抽象方法

具体类中使用抽象基类

?
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
26
27
import abc
from cStringIO import StringIO
class A(object):
  __metaclass__ = abc.ABCMeta
  @abc.abstractmethod
  def retrieve_values(self, input):
    pirnt 'base class reading data'
    return input.read()
class B(A):
  def retrieve_values(self, input):
    base_data = super(B, self).retrieve_values(input)
    print 'subclass sorting data'
    response = sorted(base_data.splitlines())
    return response
input = StringIO("""line one
line two
line three
""")
reader = B()
print reader.retrieve_values(input)

打印结果

?
1
2
3
base class reading data
subclass sorting data
['line one', 'line two', 'line three']

可以使用super来重用抽象基类中的罗辑, 但会迫使子类提供覆盖方法.

抽象属性

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import abc
class A(object):
  __metaclass__ = abc.ABCMeta
  @abc.abstractproperty
  def value(self):
    return 'should never get here.'
class B(A):
   
  @property
  def value(self):
    return 'concrete property.'
try:
  a = A()
  print 'A.value', a.value
except Exception, err:
  print 'Error: ', str(err)
b = B()
print 'B.value', b.value

打印结果,A不能被实例化,因为只有一个抽象的property getter method.

?
1
2
Error: ...
print concrete property

定义抽象的读写属性

?
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import abc
class A(object):
  __metaclass__ = abc.ABCMeta
  def value_getter(self):
    return 'Should never see this.'
  def value_setter(self, value):
    return
  value = abc.abstractproperty(value_getter, value_setter)
class B(A):
   
  @abc.abstractproperty
  def value(self):
    return 'read-only'
class C(A):
  _value = 'default value'
  def value_getter(self):
    return self._value
  def value_setter(self, value):
    self._value = value
  value = property(value_getter, value_setter)
try:
  a = A()
  print a.value
except Exception, err:
  print str(err)
try:
  b = B()
  print b.value
except Exception, err:
  print str(err)
c = C()
print c.value
c.value = 'hello'
print c.value

打印结果, 定义具体类的property时必须与抽象的abstract property相同。如果只覆盖其中一个将不会工作.

?
1
2
3
4
error: ...
error: ...
print 'default value'
print 'hello'

使用装饰器语法来实现读写的抽象属性, 读和写的方法应该相同.

?
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
26
27
28
29
import abc
class A(object):
  __metaclass__ = abc.ABCMeta
  @abc.abstractproperty
  def value(self):
    return 'should never see this.'
  @value.setter
  def value(self, _value):
    return
class B(A):
  _value = 'default'
  @property
  def value(self):
    return self._value
  @value.setter
  def value(self, _value):
    self._value = _value
b = B()
print b.value    # print 'default'
b.value = 'hello'
print b.value    # print 'hello'

在Python中定义和使用抽象类的方法相关推荐

  1. python中def什么时候用_Python中定义函数def的使用方法

    Python中定义函数def的使用方法 发布时间:2020-12-15 09:26:24 来源:亿速云 阅读:71 作者:小新 这篇文章给大家分享的是有关Python中定义函数def的使用方法的内容. ...

  2. Python如何定义接口和抽象类

    更多编程教程请到:菜鸟教程 https://www.piaodoo.com/ 友情链接: 高州阳光论坛https://www.hnthzk.com/ 人人影视http://www.op-kg.com/ ...

  3. python中定义类

    3.2. 定义类 Python是完全面向对象的:可以定义自已的类,从自已的或内置类进行继承,然后对生成的类进行实例化. 在Python中定义类很简单:就象定义函数,没有独立的定义接口.只要定义类,然后 ...

  4. python中变量名有哪些_Python变量范围有哪些?如何在Python中定义变量?

    Python变量范围有哪些?如何在Python中定义变量?在Python编程语言中,变量的范围是该变量可见或可访问的那段代码.更准确地说,不是每个程序的每个部分都可以访问所有变量.而且,有时范围也是持 ...

  5. python中定义函数常用关键字_Python 中定义函数的关键字是 _________________ 。_学小易找答案...

    [其它]实验4-串和数组-实验任务书.docx [填空题]表达式 'abc' in ['abcdefg'] 的值为______________. [填空题]已知 x = range(1,4) 和 y ...

  6. python中定义数据结构_Python中的数据结构—简介

    python中定义数据结构 You have multiples algorithms, the steps of which require fetching the smallest value ...

  7. python中定义数据结构_Python中的数据结构。

    python中定义数据结构 I remembered the day when I made up my mind to learn python then the very first things ...

  8. python中定义结构体

    2019独角兽企业重金招聘Python工程师标准>>> python中定义结构体通过继承_ctypes中的Structure类,标准写法如下: c: struct beer_reci ...

  9. python中定义类的关键字_在Python中,定义一个类使用什么关键字?

    [多选题]技术应用的限制包括 [多选题]关于类和对象,下面说法正确的有? [判断题]温度越高,料液的粘度越小,扩散系数越大,可提高膜通量. [单选题]某企业有10台运货车,已知每台车每运行100小时平 ...

最新文章

  1. MINA系列学习-IoAccpetor
  2. 用OpenCV实现图像的水平镜像(翻转)变换和竖直镜像(翻转)变换(垂直镜像变换)的源码
  3. Redis提供的持久化机制(RDB和AOF)
  4. 作业21-加载静态文件,父模板的继承和扩展
  5. python项目部署访问特别卡_【python新人求助】flask+pymssql 通过wsgi发布到Apache,访问接口服务器卡死?...
  6. tif 高程_Global Mapper中80坐标系高程DEM与kml文件叠加实例
  7. java菱形乱码 编码_【分享】Java开发过程中中文乱码问题总结
  8. Shell同时推送代码至github和gitee的解决办法
  9. 【Luogu】P1486郁闷的出纳员(Splay)
  10. date java format_java-DateFormat
  11. 1364:Field 'sex' doesn't have a default value [ SQL语句 ]
  12. 机器学习--线性回归1_线性回归-进入迷人世界的第一步
  13. 知我者,谓我心忧,不知我者,谓我何求。何必说?
  14. 日本武士的简介与起源
  15. 在使用selenium 做IE自动化操作时 请求状态码 400【帮忙解决或者找出问题所在悬赏200】
  16. Audio基本概念及处理流程
  17. 地铁杂记 - 17寸苹果
  18. CSS:标准文档流、浮动、绝对定位—(解决有时候父元素不能自动扩展)
  19. 2022出海拉美:墨西哥电商市场现状及网红营销特点
  20. 【计算摄影】浅析图像修复背后的核心技术

热门文章

  1. Python isinstance函数 - Python零基础入门教程
  2. ld 指令c语言实现,C语言符号、指令表.doc
  3. linux路由信息预览为空,route - 显示并设置Linux中静态路由表
  4. java泛型与接口_Java泛型用于方法,类和接口
  5. java复杂性_java – 计算Big-O复杂性
  6. ogg 查看某条更新_明道云Web 6.1更新:日历视图上线
  7. java圆形泳池问题_Java实现 LeetCode 778 水位上升的泳池中游泳(二分+DFS)
  8. cron每2天跑一次_直购直测,进口新极光每2年或34000公里才需要保养一次?
  9. mac系统在云服务器地址,mac如何登陆云服务器地址
  10. 微信怎么绑定消息服务器吗,fastweixin: 极其方便的实现微信公众平台服务端开发,2行代码完成服务器绑定,3行代码实现用户消息监听...