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正则表达式re模块详解

快速入门 import re pattern = 'this' text = 'Does this text match the pattern?' match = re...

Python学习笔记之列表和成员运算符及列表相关方法详解

本文实例讲述了Python学习笔记之列表和成员运算符及列表相关方法。分享给大家供大家参考,具体如下: 列表和成员运算符 列表可以包含我们到目前为止所学的任何数据类型并且可以混合到一起。...

python字符串string的内置方法实例详解

下面给大家分享python 字符串string的内置方法,具体内容详情如下所示: #__author: "Pizer Wang" #__date: 2018/1/28 a = "Le...

python中的reduce内建函数使用方法指南

官方解释: Apply function of two arguments cumulatively to the items of iterable, from left to r...

对Python3.x版本print函数左右对齐详解

数字的情况: a = 5 , b = 5.2,c = "123456789" 最普通的右对齐:print("%3d"%a) 输出 5(详情:5前面两个空格) print("%10.3f"...