
8

Python 的抽象基类 ABC
source link: https://zhiqiang.org/coding/abstruct-base-classes-in-python.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Python 的抽象基类 ABC
Pyhon 的抽象基类( abstruct base class )库abc
定义了类似于 C++的纯虚函数的功能:
from abc import ABC, abstractmethod class Base(ABC): # 定义一个纯需函数,子类必须实现该函数,否则会在实例初始化时抛出 TypeError 异常。 @abc.abstractmethod def foo(self): print("this is foo of base, but never will be called!") # @abstractmethod 可以和 @classmethod 混用。 @classmethod @abstractmethod def bar(cls): raise NotImplementedError() class Concrete(Base): def foo(self): return 'foo() called' c = Concrete(); # will raise TypeError
这很类似于 C++的纯虚函数:
class Base { virtual void foo() = 0; virtual void bar() = 0; }; class Concrete : public Base { void foo() override { return "foo() called"; } };
使用注意事项:
- 如果没有定义
@abstractmethod
的成员函数,即使继承ABC
,也可以实例化。 - 定义为
@abstractmethod
的函数,里面的实现无法被调用,比如上面例子里,Base.foo()
或通过super()
调用都是不行的。这和 C++不一样。 @abstractmethod
可以和@staticmethod
、@classmethod
之类的修饰符联用。
Q. E. D.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK