Last Updated: 2023-04-30 09:00:12 Sunday
-- TOC --
在Python定义类似C++的interface(即纯虚类),需要使用ABC这个base class,以及@abstractmethod装饰器。
继承自ABC的类,就成了不能实例化的虚类,在class里面定义接口,用@abstractmethod装饰。再继续向下继承的类,就必须要实现所有基类中用@abstractmethod装饰的接口,否则代码会抛出异常。
举个例子:
from abc import ABC, abstractmethod
class xyz(ABC):
@abstractmethod
def show(self):
""""""
@abstractmethod
def how(self):
print('unknown...')
def what(self):
print('wtf...')
class X(xyz):
def show(self):
print('i am x...')
def how(self):
print('good...')
class Y(xyz):
def show(self):
print('i am y...')
def how(self):
super().how()
x = X()
x.show()
x.how()
x.what()
y = Y()
y.show()
y.how()
y.what()
# z = xyz() # error
用@abstractmethod装饰的接口,不一定需要写body,用pass或docstring占位都OK。也可以写个body,如上how接口。
继承了ABC的xyz还可以实现concrete interface
,继承后使用,如上的what接口。
xyz继承自ABC,class X和class Y继承自xyz,X和Y必须要实现show和how这两个抽象接口。Y的how接口的实现方式,采用了调用super,也OK,这就是给抽象接口写body的意义所在吧。
最后,xyz不可以实例化。
To understand the abstract class and method better, let us take an example. Suppose we have a few classes related to different items in a bookstore. Now our classes are books, stationery, and magazines. All these products are dealt with separately, so all of these classes must have a method named sale that could return the amount achieved by selling these items. So to ensure that each of these classes has a sale method, we will make an abstract class named bookstore with an abstract method Sale and will derive all the other three classes from it. Until we have made a method Sale in each of the derived classes, we would not be able to make its object, or the compiler will report an error.
用抽象类的接口定义,规范继承类必须要实现的接口。
本文链接:https://cs.pynote.net/sf/python/202209261/
-- EOF --
-- MORE --