Python Abstract Base Classes
Define interfaces using abstract base classes.
Create interfaces and enforce contracts.
Basic ABC
```python from abc import ABC, abstractmethod
class Animal(ABC): @abstractmethod def speak(self): pass @abstractmethod def move(self): pass
class Dog(Animal): def speak(self): return "Woof!" def move(self): return "Running"
dog = Dog() print(dog.speak()) # Woof!
animal = Animal() # Error! Can't instantiate ```
Abstract Properties
```python from abc import ABC, abstractmethod
class Shape(ABC): @property @abstractmethod def area(self): pass
class Rectangle(Shape): def __init__(self, width, height): self.width = width self.height = height @property def area(self): return self.width * self.height
rect = Rectangle(10, 20) print(rect.area) # 200 ```
Multiple Abstract Methods
```python from abc import ABC, abstractmethod
class Database(ABC): @abstractmethod def connect(self): pass @abstractmethod def disconnect(self): pass @abstractmethod def query(self, sql): pass
class PostgreSQL(Database): def connect(self): print("Connected to PostgreSQL") def disconnect(self): print("Disconnected") def query(self, sql): print(f"Running: {sql}")
db = PostgreSQL() db.connect() db.query("SELECT * FROM users") ```
Check Subclass
```python from abc import ABC
class Vehicle(ABC): pass
class Car(Vehicle): pass
print(issubclass(Car, Vehicle)) # True print(isinstance(Car(), Vehicle)) # True ```
Remember
- Use ABC for interfaces - Abstract methods must be implemented - Can't instantiate abstract classes