Lesson 10 of 20

Functions & Classes

Classes & Objects

3 min read

Classes let you bundle data and functionality together. AI frameworks like LangChain use classes extensively for agents, tools, and memory.

Basic Class Structure

class Agent:
    """A simple AI agent."""

    def __init__(self, name, model):
        """Initialize the agent."""
        self.name = name    # Instance attribute
        self.model = model
        self.history = []   # Each instance has its own history

    def chat(self, message):
        """Send a message and get a response."""
        self.history.append({"role": "user", "content": message})
        response = f"[{self.name}]: I received your message."
        self.history.append({"role": "assistant", "content": response})
        return response

# Creating instances
agent1 = Agent("Claude", "claude-3-opus")
agent2 = Agent("GPT", "gpt-4")

# Using the instance
response = agent1.chat("Hello!")
print(agent1.history)

The self Parameter

self refers to the current instance. It's how methods access instance data:

class Counter:
    def __init__(self):
        self.count = 0  # Belongs to this instance

    def increment(self):
        self.count += 1  # Access via self

    def get_count(self):
        return self.count

c1 = Counter()
c2 = Counter()

c1.increment()
c1.increment()
print(c1.get_count())  # 2
print(c2.get_count())  # 0 (separate instance)

Class vs Instance Attributes

class Model:
    # Class attribute (shared by all instances)
    api_version = "v1"

    def __init__(self, name):
        # Instance attribute (unique to each instance)
        self.name = name

m1 = Model("gpt-4")
m2 = Model("claude")

print(m1.api_version)  # "v1"
print(m2.api_version)  # "v1"
print(m1.name)         # "gpt-4"
print(m2.name)         # "claude"

Practical Example: Tool Class

class Tool:
    """Base class for agent tools."""

    def __init__(self, name, description):
        self.name = name
        self.description = description

    def execute(self, **kwargs):
        raise NotImplementedError("Subclasses must implement execute()")

class SearchTool(Tool):
    """A web search tool."""

    def __init__(self):
        super().__init__(
            name="web_search",
            description="Search the web for information"
        )

    def execute(self, query):
        # Actual search implementation would go here
        return f"Search results for: {query}"

# Usage
search = SearchTool()
result = search.execute(query="Python tutorials")

Special Methods

class Message:
    def __init__(self, role, content):
        self.role = role
        self.content = content

    def __str__(self):
        """Human-readable string representation."""
        return f"{self.role}: {self.content}"

    def __repr__(self):
        """Developer-friendly representation."""
        return f"Message(role='{self.role}', content='{self.content}')"

msg = Message("user", "Hello")
print(msg)      # "user: Hello" (uses __str__)
print(repr(msg))  # "Message(role='user', content='Hello')"

Next, we'll learn about dataclasses—a simpler way to define data-holding classes. :::

Quiz

Module 3: Functions & Classes

Take Quiz