Python抽象类的新写法
2015-06-18 00:00
666 查看
记得之前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的time模块中的常用方法整理
- 举例详解Python中threading模块的几个常用方法
- Python自然语言处理(1):初识NLP
- python模块MySQLdb
- 21行Python写出拼写检查器
- python scrapy爬取动态页面
- Python学习笔记之基本语法
- 20150617-Python,Django安装
- 20150617-Python冒泡排序
- python可变参数调用函数的问题
- 使用android模拟事件,python完成自动化测试
- python学习笔记
- Python 装饰器
- Leetcode—Contains Duplicate II—Python
- Leetcode—Contains Duplicate—Python的三种写法
- 用Python提取XML里的内容,存到Excel中
- 机器学习算法与Python实践之(七)逻辑回归(Logistic Regression)
- Django1.8+Python3.4+Mysql5.5
- Python正则表达式操作指南
- [python]Python中变量的作用域(variable scope)