• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python抽象类的新写法

python 搞代码 4年前 (2022-01-07) 31次浏览 已收录 0个评论

这篇文章主要介绍了Python抽象类的新写法,本文讲解了老版本中的hack方式实现抽象类,以及2.7以后使用abstractmethod模块写抽象类的方法,需要的朋友可以参考下

记得之前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 "", line 1, in  File "", 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(): __metacl<em style="color:transparent">来源gao.dai.ma.com搞@代*码网</em>ass__ = ABCMeta @abstractmethod def bar(self): pass

运行效果

 >>> class B(Foo): ... def bar(self): ... pass ... >>> B()  >>> B().bar() >>> class C(Foo): ... pass ... >>> C().bar() Traceback (most recent call last): File "", line 1, in  TypeError: Can't instantiate abstract class C with abstract methods bar >>> 

以上就是Python抽象类的新写法的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python抽象类的新写法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址