from abc import ABC, abstractmethod
class A(ABC):
def __init__(self, name):
self.something = name
@abstractmethod
def something():
pass
class B(A):
pass
I'm still new to learning OOP so I would to ask this. I know that an abstract class is considered a superclass, but can an abstract class be a subclass as well?
Using the code as an example, B
inherits from A
but does not override the abstract methods in A
, so does this mean that B
is still considered an abstract class as well as as a subclass of A
?
CodePudding user response:
First, what is an abstract class? It is a class that is to be used as a "skeleton" for a subclass. Now to your question....
So does this mean that B is still considered an abstract class as well as as a subclass of A?
Yes, because all of the methods are not overridden, and they are abstract.
Take this code for example:
from abc import ABC, abstractmethod
class A(ABC):
@abstractmethod
def foo(self):
pass
@abstractmethod
def bar(self):
pass
class B(A):
def foo(self):
return 'Foo implementation'
Here, the class B
is still abstract since one of the methods is not overridden that is abstract. So if you try to create an instance of that, you'll get this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class InstrumentName with abstract methods bar
Here we can see that this class inherits from A
, but is a concrete class, since the methods are overridden:
class C(A):
def foo(self):
pass
def bar(self):
pass
c = C()
c.foo()
This code runs without errors.
In short, a subclass of an abstract class is still an abstract class as long as the methods are not overridden.
CodePudding user response:
Yes. As long as you don't override all the abstract methods, the subclass is still abstract.