Обложка канала

Библиотека Python разработчика

20835 @BookPython

Библиотека Python разработчика. Книги по программированию на Python.

Библиотека Python разработчика

4 года назад
Открыть в
The popular method to declare an abstract method in Python is to use NotImplentedError exception: def human_name(self): raise NotImplementedError Though it's pretty popular and even has IDE support (PyCharm considers such method to be abstract), this approach has a downside. You get the error only upon method call, not upon class instantiation. Use abc to avoid this problem: from abc import ABCMeta, abstractmethod class Service(metaclass=ABCMeta): @abstractmethod def human_name(self): pass Also be aware that NotImplemented is not the same that NotImplementedError. It's not even an exception. It's a special value (like True and False) that has an absolutely different meaning. Some special methods may return it (e.g., __eq__(), __add__(), etc.) so Python tries to reflect operation. If a.__add__(b) returns NotImplemented, Python tries to call b.__radd__.