Python抽象类与抽象方法

抽象方法

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

实现

In [19]: from abc import ABC, abstractmethod

In [20]: class A(object):
    ...:     '''
    ...:     抽象类
    ...:     '''
    ...:     @abstractmethod
    ...:     def fun1(self):
    ...:         pass
    ...:     @abstractmethod
    ...:     def fun2(self):
    ...:         pass
    ...:     

In [21]: a = A()

In [22]: a
Out[22]: <__main__.A at 0x105cb8198>

In [23]: class B(A):
    ...:     '''
    ...:     继承抽象类
    ...:     '''
    ...:     
    ...:     pass

In [24]: b = B()

In [25]: b
Out[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)
30-bb7a6e918aa7> in ()
----> 1 b = B()

TypeError: Can't instantiate abstract class B with abstract methods fun1, fun2

In [31]: class B(A):
    ...:     def fun1(self):
    ...:         print('fun1')

In [32]: b = B()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in ()
----> 1 b = B()

TypeError: Can't instantiate abstract class B with abstract methods fun2

你可能感兴趣的:(python)