Abstract class instantiatedPYL-E0110
An attempt was made to create an instance of an abstract class that contains abstract methods. This will raise a TypeError
because abstract classes are meant to serve as templates and cannot be instantiated directly until all their abstract methods are implemented.
Abstract classes in Python, defined using abc.ABCMeta
as metaclass, serve as base classes that declare abstract methods which must be implemented by their concrete subclasses. Trying to create an instance of an abstract class will raise: TypeError: Can't instantiate abstract class <class_name> with abstract methods <method_name>
.
Here's an example of incorrect usage:
from abc import ABCMeta, abstractmethod
class Shape(metaclass=ABCMeta):
@abstractmethod
def area(self):
pass
# This will raise TypeError
shape = Shape() # TypeError: Can't instantiate abstract class Shape with abstract methods area
To fix this, you need to either create a concrete subclass that implements all abstract methods, or remove the @abstractmethod
decorator if the class is meant to be instantiated.
Common scenarios where this error occurs:
- Accidentally instantiating the base class instead of a subclass
- Forgetting to implement all abstract methods in a subclass
- Using
@abstractmethod
on methods that should be concrete - Misunderstanding the purpose of abstract classes
Remember:
- Abstract classes are meant to be inherited from, not instantiated
- All abstract methods must be implemented in concrete subclasses
- Abstract methods define an interface that subclasses must follow
- If you need to create instances directly, don't mark the class or its methods as abstract