1. 程式人生 > 實用技巧 >Python 定義介面和抽象類

Python 定義介面和抽象類

JAVA由於不支援多繼承,故創造了介面這個概念來解決這個問題。而Python本身是支援多繼承的,故在Python中,沒有介面這種類,只有這個概念而已,只不過Python中的介面實現,是通過多繼承實現的。

解決方案

使用abc模組可以很輕鬆的定義抽象基類:

from abc import ABCMeta, abstractmethod
 
class IStream(metaclass=ABCMeta):
  @abstractmethod
  def read(self, maxbytes=-1):
    pass
 
  @abstractmethod
  def write(self, data):
    
pass

抽象類的一個特點是它不能直接被例項化,比如你想像下面這樣做是不行的

a = IStream() # TypeError: Can't instantiate abstract class
        # IStream with abstract methods read, write

類繼承介面:

class SocketStream(IStream):
  def read(self, maxbytes=-1):
    pass
 
  def write(self, data):
    pass

除了繼承這種方式外,還可以通過註冊方式來讓某個類實現抽象基類:

import
io # Register the built-in I/O classes as supporting our interface IStream.register(io.IOBase) # Open a normal file and type check f = open('foo.txt') isinstance(f, IStream) # Returns True