Python抽象类与抽象方法

来源:互联网 发布:淘宝外卖点麻辣烫两人 编辑:程序博客网 时间:2024/05/17 06:15

抽象方法

抽象方法表示基类的一个方法,没有实现,所以基类不能实例化,子类实现了该抽象方法才能被实例化。
Python的abc提供了@abstractmethod装饰器实现抽象方法,下面以Python3的abc模块举例。

实现

In [19]: from abc import ABC, abstractmethodIn [20]: class A(object):    ...:     '''    ...:     抽象类    ...:     '''    ...:     @abstractmethod    ...:     def fun1(self):    ...:         pass    ...:     @abstractmethod    ...:     def fun2(self):    ...:         pass    ...:     In [21]: a = A()In [22]: aOut[22]: <__main__.A at 0x105cb8198>In [23]: class B(A):    ...:     '''    ...:     继承抽象类    ...:     '''    ...:         ...:     passIn [24]: b = B()In [25]: bOut[25]: <__main__.B at 0x105cd1a58>
  • 注意此处抽象方法没有起到作用,因为抽象类没有继承ABC
In [28]: class A(ABC):    ...:     '''    ...:     抽象类    ...:     '''    ...:     @abstractmethod    ...:     def fun1(self):    ...:         pass    ...:     @abstractmethod    ...:     def fun2(self):    ...:         pass    ...:     In [29]: class B(A):    ...:     pass    ...: In [30]: b = B()---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-30-bb7a6e918aa7> in <module>()----> 1 b = B()TypeError: Can't instantiate abstract class B with abstract methods fun1, fun2In [31]: class B(A):    ...:     def fun1(self):    ...:         print('fun1')In [32]: b = B()---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-32-bb7a6e918aa7> in <module>()----> 1 b = B()TypeError: Can't instantiate abstract class B with abstract methods fun2
原创粉丝点击