8

Python 的抽象基类 ABC

 4 years ago
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.
neoserver,ios ssh client

Python 的抽象基类 ABC

作者: 张志强

, 发表于 2021-03-11

, 共 935 字 , 共阅读 46 次

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK