abstract class python
- Abstract classes are classes that contain one or more abstract methods.
- An abstract method is a method that is declared but contains no implementation.
- Abstract classes cannot be instantiated and require subclasses to provide implementations for the abstract methods.
TypeError: Can't instantiate abstract class <className> with abstract methods <methodName>
- The class can not be instantiated (not able to create an object of that class) and contain at least one abstract method called abstract classes. if you try to create an object of the abstract class, you will get an error
When we matter input and output, we don’t need to understand the background mechanism of that process in such a scenario abstraction is used.
The following Python code uses the
abc module and defines an abstract base class.
abstract class in python
from abc import ABC, abstractmethod class AbstractClassExample(ABC): def __init__(self, value): self.value = value super().__init__() @abstractmethod def do_something(self): pass
Must override the method. Otherwise, it will error out. A class that is derived from an abstract class cannot be instantiated unless all of its abstract methods are overridden.
class doAdd(AbstractClassExample): def do_something(self): return self.value + 42 x = doAdd(10) print(x.do_something())