Object-Oriented Programming (OOP)
OOP is a paradigm based on "objects" which contain data (attributes) and code (methods). The four core principles are: 1. **Encapsulation**: Hiding internal sta...
Definition
OOP is a paradigm based on "objects" which contain data (attributes) and code (methods). The four core principles are:
- Encapsulation: Hiding internal state details.
- Inheritance: Creating child classes from parent classes to share attributes.
- Polymorphism: Overriding parent methods in child classes to implement unique behaviors.
- Abstraction: Hiding background implementation complexity.
Why It Exists
Integrating multiple AI providers (OpenAI, Gemini, local models) requires a unified contract. OOP enables you to abstract the specific API differences behind a parent class interface, allowing the rest of your app to remain provider-agnostic.
How It Works
BASE LLM INTERFACE (Abstraction Class)
┌──────────────────────────────┐
│ AbstractLLMClient │
├──────────────────────────────┤
│ + generate_text(prompt) │
└──────────────┬───────────────┘
│
┌──────────────┴──────────────┐
▼ ▼
┌──────────────────┐ ┌──────────────────┐
│ GeminiClient │ │ OpenAIClient │
├──────────────────┤ ├──────────────────┤
│ (Polymorphic- │ │ (Polymorphic- │
│ Gemini API Call)│ │ OpenAI API Call)│
└──────────────────┘ └──────────────────┘
1. **Interfaces**: Define abstract base classes using Python's `abc` module.
2. **Polymorphic Dispatch**: At runtime, Python looks up the specific child instance method to execute, decoupling client execution logic.Real-World Example
In LangChain, the class BaseLLM acts as an abstract base. Specific subclasses like ChatOpenAI, ChatGemini, and HuggingFacePipeline inherit from it and implement the raw HTTP requests under the hood.
Python Example
Here is a production abstraction interface representing a unified LLM Client structure:
from abc import ABC, abstractmethod
from typing import Dict, Any
class BaseLLMClient(ABC):
"""Abstract Base Class serving as the contract for all LLM providers."""
def __init__(self, api_key: str):
self.api_key = api_key
@abstractmethod
def generate(self, prompt: str) -> str:
"""Sends prompt to the provider and returns parsed output string."""
pass
class OpenAIClient(BaseLLMClient):
"""Specific implementation using OpenAI REST interfaces."""
def generate(self, prompt: str) -> str:
# Represents custom headers and endpoints for OpenAI API calls
return f"OpenAI Response: [System processed: '{prompt}']"
class GeminiClient(BaseLLMClient):
"""Specific implementation using Google Gemini REST interfaces."""
def generate(self, prompt: str) -> str:
# Represents custom JSON formats for Gemini API calls
return f"Gemini Response: [System processed: '{prompt}']"
# Orchestrator doesn't care about specific provider backend details
def execute_agent_step(client: BaseLLMClient, prompt: str):
print(client.generate(prompt))
if __name__ == "__main__":
openai = OpenAIClient("sk-openai-key")
gemini = GeminiClient("AIzaSy-key")
execute_agent_step(openai, "Hello")
execute_agent_step(gemini, "Hello")Interview Questions
- Beginner: Name the 4 core principles of OOP.
- Intermediate: What is an Abstract Base Class (ABC) in Python, and how is it defined?
- Advanced: Explain how Python handles Multiple Inheritance. What is Method Resolution Order (MRO)?
Interview Answers
- Beginner: The 4 principles are Encapsulation (data hiding), Inheritance (reusing code), Polymorphism (multiple implementations), and Abstraction (simplifying interfaces).
- Intermediate: An ABC defines a template blueprint for other classes. It prevents instantiation of the base class itself and uses
@abstractmethoddecorators to force child classes to implement specific methods. Defined using theabcmodule. - Advanced: Multiple inheritance allows a class to inherit from more than one parent. Python resolves method conflicts using Method Resolution Order (MRO) defined by the C3 Linearization algorithm. You can check this order for any class using the
__mro__attribute or.mro()method.
Common Mistakes
- Instantiating base class: Attempting to run
client = BaseLLMClient()directly. ABCs are strictly interfaces and cannot be instantiated directly without subclasses.
Assignment
Extend the Python example by building a third child class called ClaudeClient that overrides the generate method, return a custom text string structure.