A class is an abstract class if it is used to represent another class. The abstract class cannot be instantiated on its own and is meant to be subclassed by other classes. Likewise, a method is an abstract method if it is declared but not implemented in the abstract class. To put it simply, an abstract method is a method that is created but not used in the abstract class, but every subclass must implement this method.
An abstract class can consist of both fully-implemented methods (called concrete methods) and abstract methods. Every latter subclass defined must contain the abstract methods and their actual implementations.
<aside> 💡
An abstract class does not create instances (or objects), and serves as a blueprint for subclasses, which will provide implementations for the abstract methods defined in the abstract class. While the abstract method serves as a structure and will have its implementation provided in the subclasses.
</aside>
This is an example of a abstract class and abstract method:
# Abstract Class Animal
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self): # Abstract method,
# since there is no implementation
pass
A abstract class with concrete method and abstract method:
# Abstract Class Animal
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def greets(self): # Abstract method,
# since there is no implementation
pass
@staticmethod
def name(): # Concrete method
return "This is an animal"
If we try to create an instance with class Animal
:
def main():
# Error: Cannot create object from an abstract class
animal = Animal()
print(animal.name())
main()
Output:
Traceback (most recent call last):
File "/Users/macbook/Documents/Code Python/Practice/Practice - ObjectOriented/ClassAbstractAnimal.py", line 20, in <module>
main()
File "/Users/macbook/Documents/Code Python/Practice/Practice - ObjectOriented/ClassAbstractAnimal.py", line 16, in main
animal = Animal()
^^^^^^^^
TypeError: Can't instantiate abstract class Animal without an implementation for abstract method 'greets'
Optional: Use return NotImplemented
instead of pass
.
# Abstract Class Animal
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def greets(self): # Abstract method,
# since there is no implementation
return NotImplemented
@staticmethod
def name(): # Concrete method
return "This is an animal"
Optional: Use ABCMeta
instead of ABC