python abstract class

python abstract class

In Python, an abstract class is a special kind of class that cannot be instantiated on its own. It is used as a blueprint for creating other classes. The idea behind abstract classes is to provide a common interface for a set of related classes, allowing the user to interact with objects of those classes in a uniform way.

An abstract class is defined using the abc (Abstract Base Class) module in Python. The abstract class is created by inheriting from the ABC class provided by the abc module and marking methods as abstract using the @abstractmethod decorator. These methods are then required to be implemented by any concrete (non-abstract) subclass that is derived from the abstract class.

Here's a simple example of an abstract class in Python

python
from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass @abstractmethod def perimeter(self): pass class Rectangle(Shape): def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height def perimeter(self): return 2 * (self.width + self.height)


In this example, the Shape class is an abstract class that defines two abstract methods: area and perimeter. The Rectangle class is a concrete subclass that implements these methods. Since the abstract methods are defined in the abstract class, any concrete subclass that is derived from it must also implement those methods.

Comments

Popular posts from this blog

Market share of top programming languages python, java

python NumPy - Data science