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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With