Python 中没有接口的正式语法支持,但是 Python 有抽象类的概念。
抽象类是一个特殊的类,它的特殊之处在于只能被继承,不能被实例化。如果说类是从一堆对象中抽取相同的内容而来的,那么抽象类就是从一堆类中抽取相同的内容而来的,内容包括数据属性和函数属性。

抽象是为了继承,接口继承实质上是要求,“做出一个良好的抽象,这个抽象规定了一个兼容接口,使得外部调用者无需关心具体细节,可一视同仁的处理实现了特定接口的所有对象”。这在程序设计上,叫做归一化。即基于同一个接口实现的类,这些类产生的对象在使用时,用法一样。

抽象类的一些特性:

  • 抽象类不能被实例化。
  • 抽象类中不一定包含抽象方法,但是有抽象方法的类必定是抽象类。
  • 抽象类的子类必须给出抽象类中的抽象方法的具体实现,除非该子类也是抽象类。
  • 在继承抽象类的过程中,应该尽量避免多继承;而在继承接口的时候,反而使用多继承。(接口隔离原则)

Python 中实现抽象类,需要使用 abc 模块。
Python 3+

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from abc import ABCMeta, abstractmethod

class People(metaclass=ABCMeta):
@abstractmethod
def name(self):
pass

class Teacher(People):
@property
def name(self):
return 'lizs'

People()
TypeError: Can't instantiate abstract class People with abstract methods name
Teacher().name # lizs

Python 2.7

1
2
3
4
5
6
7
8
9
class People(object):
__metaclass__ = ABCMeta

@abstractmethod
def name(self):
pass

People()
TypeError: Can't instantiate abstract class People with abstract methods name

为了兼容 Python 2 和 Python 3,使用six模块。

1
2
3
4
5
6
7
8
9
10
from abc import ABCMeta
import six

@six.add_metaclass(ABCMeta)
class People(object):
def name(self):
pass

People()
TypeError: Can't instantiate abstract class People with abstract methods name