Python抽象类的新写法

yipeiwu_com6年前Python基础

记得之前learn python一书里面,因为当时没有官方支持,只能通过hack的方式实现抽象方法,具体如下 最简单的写法

class MyCls():
  def foo(self):
    print('method no implement')

运行的例子


>>> a = MyCls()
>>> a.foo()
method no implement
>>>

这样虽然可以用,但是提示不明显,还是容易误用,当然,还有更好的方法 较为可以接受的写法

class MyCls():
  def foo(self):
    raise Exception('no implement exception', 'foo method need implement')

一个简单的用例

>>> a = MyCls()
>>> a.foo()
Traceback (most recent call last):
 File "<interactive input>", line 1, in <module>
 File "<clipboard>", line 3, in foo
Exception: ('no implement exception', 'foo method need implement')

这就是2.7之前的写法了,2.7给了我们新的支持方法!abc模块(abstruct base class),这个在py3k中已经实现,算是back port吧。

我们来看看新的写法

from abc import ABCMeta
 
from abc import ABCMeta,abstractmethod
 
class Foo():
  __metaclass__ = ABCMeta
  @abstractmethod
  def bar(self):
    pass

运行效果

>>> class B(Foo):
... def bar(self):
... pass
... 
>>> B()
<__main__.B object at 0x02EE7B50>
>>> B().bar()
>>> class C(Foo):
... pass
... 
>>> C().bar()
Traceback (most recent call last):
 File "<interactive input>", line 1, in <module>
TypeError: Can't instantiate abstract class C with abstract methods bar
>>> 


相关文章

python如何给字典的键对应的值为字典项的字典赋值

问题 1:需要得到一个类似{“demo”:{“key”:”value”}}这样格式的字典dic。 dic = dict() dic_temp = dict() dic_temp =...

Pyinstaller将py打包成exe的实例

Pyinstaller将py打包成exe的实例

背景:分享python编写的小脚本时,拷贝代码还缺各种环境,使用Pyinstaller将py可以打包成exe,直接运行即可 1、安装pyinstaller运行时所需要的windows拓展...

Python 堆叠柱状图绘制方法

Python 堆叠柱状图绘制方法

本文介绍了Python 堆叠柱状图绘制方法,分享给大家,具体如下: ''''''''''''''''''''''''''''''''''''''''''''''''''''''''...

python使用post提交数据到远程url的方法

本文实例讲述了python使用post提交数据到远程url的方法。分享给大家供大家参考。具体如下: import sys, urllib2, urllib zipcode = "S2...

django数据库migrate失败的解决方法解析

django数据库migrate失败的解决方法解析

Django是一个MVC架构的web框架,其中,数据库就是“Module”。使用这种框架,我们不必写一条SQL语句,就可以完成对数据库的所有操作。在之前的Django版本中,我们像操作本...