脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python抽象类的新写法

Python抽象类的新写法

2020-07-16 10:35脚本之家 Python

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

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

?
1
2
3
4
5
6
7
8
9
10
11
class MyCls():
  def foo(self):
    print('method no implement')
 
运行的例子
 
 
>>> a = MyCls()
>>> a.foo()
method no implement
>>>

 

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

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

 

一个简单的用例

?
1
2
3
4
5
6
>>> 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吧。

我们来看看新的写法

?
1
2
3
4
5
6
7
8
9
from abc import ABCMeta
 
from abc import ABCMeta,abstractmethod
 
class Foo():
  __metaclass__ = ABCMeta
  @abstractmethod
  def bar(self):
    pass

运行效果

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> 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
>>>

延伸 · 阅读

精彩推荐