Object-Oriented Programming (OOP)

MEDIUM3 min readby AdminJune 20, 2026History
0.0|0 ratingsLog in to rate

OOP is a paradigm based on "objects" which contain data (attributes) and code (methods). The four core principles are: 1. **Encapsulation**: Hiding internal sta...

#ai-engineering#course#object-oriented

Definition

OOP is a paradigm based on "objects" which contain data (attributes) and code (methods). The four core principles are:

  1. Encapsulation: Hiding internal state details.
  2. Inheritance: Creating child classes from parent classes to share attributes.
  3. Polymorphism: Overriding parent methods in child classes to implement unique behaviors.
  4. 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

python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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

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

Example

Here is a production abstraction interface representing a unified LLM Client structure:

python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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 @abstractmethod decorators to force child classes to implement specific methods. Defined using the abc module.
  • 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.


Discussion

Join the discussion! Sign in to leave comments and ask questions.

Loading discussion...