Chapter 7: Object-Oriented Programming in Python for AI
Introduction
Object-Oriented Programming (OOP) is a powerful paradigm in Python that helps structure AI projects efficiently. It allows developers to encapsulate functionality, reuse code, and build scalable AI models. In this chapter, we will explore classes, objects, encapsulation, inheritance, polymorphism, and dataclasses, focusing on how they help in AI development.
💡 Real-world analogy: OOP in Python is like building modular LEGO blocks—each block (class) has a specific function, and we can combine them to create complex AI systems.
Classes and Objects – Why They Matter in AI
A class is a blueprint for creating objects, and an object is an instance of a class. OOP helps organize AI code into logical units, making it reusable and scalable.
1️⃣ Defining a Class and Creating an Object
class AIModel:
def __init__(self, name, accuracy):
self.name = name
self.accuracy = accuracy
def evaluate(self):
return f"{self.name} model has {self.accuracy}% accuracy."
# Creating an instance (object)
model = AIModel("GPT-4", 92.5)
print(model.evaluate()) # Output: GPT-4 model has 92.5% accuracy.
💡 Use Case: Classes help in defining AI models as objects, allowing structured AI workflows.
Encapsulation – Protecting AI Model Data
Encapsulation hides the internal details of an object and restricts direct modification of variables.
2️⃣ Private Attributes and Getters/Setters
class SecureAI:
def __init__(self, name, accuracy):
self.__accuracy = accuracy # Private attribute
def get_accuracy(self):
return self.__accuracy
def set_accuracy(self, value):
if 0 <= value <= 100:
self.__accuracy = value
else:
print("Invalid accuracy value")
# Creating an object
secure_model = SecureAI("ResNet", 90)
print(secure_model.get_accuracy()) # Output: 90
💡 Use Case: Encapsulation is useful in AI projects to prevent accidental modification of critical parameters like accuracy or hyperparameters.
Inheritance – Reusing AI Model Code
Inheritance allows us to create a new class based on an existing class, avoiding code duplication.
3️⃣ Example of Inheritance
class BaseModel:
def __init__(self, name):
self.name = name
def train(self):
return f"Training {self.name} model..."
# Derived class
class CNNModel(BaseModel):
def __init__(self, name, layers):
super().__init__(name)
self.layers = layers
def details(self):
return f"{self.name} has {self.layers} layers."
cnn = CNNModel("ResNet", 50)
print(cnn.train()) # Output: Training ResNet model...
print(cnn.details()) # Output: ResNet has 50 layers.
💡 Use Case: Inheritance is used to define base AI models and extend them with specific architectures (e.g., CNN, RNN, Transformer).
Polymorphism – Flexibility in AI Model Design
Polymorphism allows different classes to share the same method name but behave differently.
4️⃣ Example of Polymorphism
class AIModel:
def evaluate(self):
pass # Method to be implemented by subclasses
class CNN(AIModel):
def evaluate(self):
return "Evaluating CNN model."
class RNN(AIModel):
def evaluate(self):
return "Evaluating RNN model."
models = [CNN(), RNN()]
for model in models:
print(model.evaluate())
💡 Use Case: Polymorphism is useful for handling multiple AI architectures with a common interface.
Using Dataclasses for AI Model Configurations
Dataclasses simplify the process of defining classes and storing AI parameters efficiently.
5️⃣ Example of Dataclass
from dataclasses import dataclass
@dataclass
class ModelConfig:
name: str
learning_rate: float
batch_size: int
config = ModelConfig("Transformer", 0.001, 32)
print(config)
💡 Use Case: Dataclasses are ideal for storing hyperparameters, model configurations, and training metadata.
Best Practices for OOP in AI
✅ Use classes to structure AI models and workflows. ✅ Encapsulate critical model parameters to prevent unintended changes. ✅ Leverage inheritance for reusable base models. ✅ Use dataclasses for clean AI configuration storage.
Conclusion
OOP helps organize AI code into modular, reusable components, making machine learning and deep learning projects more manageable. By using encapsulation, inheritance, polymorphism, and dataclasses, we can design scalable AI architectures.
In the next chapter, we will explore functional programming in Python and how it complements AI workflows.