Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "ABC" class do?

I wrote a class that inherits another class:

class ValueSum(SubQuery):
    output = IntegerField()

And pycharm is showing the following warning:

Class ValueSum must implement all abstract methods

Then I alt+enter to add ABC to superclass. And my warning is gone. I have several questions:

  • Should I always do this when writing a sub-class?

  • What is the difference between manually implementing all the methods vs just using ABC?

  • Does ABC add something to my code?

like image 596
nonsensei Avatar asked Dec 23 '22 18:12

nonsensei


1 Answers

SubQuery is an abstract base class (per the abc module) with one or more abstract methods that you did not override. By adding ABC to the list of base classes, you defined ValueSum itself to be an abstract base class. That means you aren't forced to override the methods, but it also means you cannot instantiate ValueSum itself.

PyCharm is warning you ahead of time that you need to implement the abstract methods inherited from SubQuery; if you don't, you would get an error from Python when you actually tried to instantiate ValueSum.


As to what inheriting from ABC does, the answer is... not much. It's a convenience for setting the metaclass. The following are equivalent:

class Foo(metaclass=abc.ABCMeta):
    ...

and

class Foo(abc.ABC):
    ...

The metaclass modifies __new__ so that every attempt to create an instance of your class checks that the class has implemented all methods decorated with @abstractmethod in a parent class.

like image 172
chepner Avatar answered Jan 02 '23 14:01

chepner