Interface Class

定义接口及抽象基类

接口(interface)和抽象类(abstract class)的作用在于,可以通过定义接口抽象基类来实现确保子类实现了某些特定的方法

from abc import ABCMeta, abstractmethod

class fileio(metaclass=ABCMeta):
    @abstractmethod
    def read(self, maxbytes=-1):
        pass

    @abstractmethod
    def write(self, data):
        pass


f = fileio()

抽象类有个特点,就是不能实例化

Traceback (most recent call last):
  File "F:/Python/Learn Through/oop1.py", line 94, in <module>
    f = fileio()
TypeError: Can't instantiate abstract class fileio with abstract methods read, write

抽象类的目的就是让其他类继承并且实现特定的方法

from abc import ABCMeta, abstractmethod

class fileio(metaclass=ABCMeta):
    @abstractmethod
    def read(self, maxbytes=-1):
        pass

    @abstractmethod
    def write(self, data):
        pass


class text(fileio):
    def read(self, maxbytes=-1):
        print('read')
    def write(self, data):
        print(data)

t = text()
t.write('123')

输出

123

如果继承抽象类的子类没有实现对应的方法,在运行时则会报错

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

    @abstractmethod
    def write(self, data):
        pass

class text(fileio):
    def read(self, maxbytes=-1):
        print('read')
    def writa(self, data):
        print(data)
    def update(self):
        print('update')

t = text()
t.write(123)

输出

Traceback (most recent call last):
  File "F:/Python/Learn Through/oop1.py", line 100, in <module>
    t = text()
TypeError: Can't instantiate abstract class text with abstract methods write

results matching ""

    No results matching ""