Open in VS Code: From your cloned s26-06643 repository, run in the terminal:

code sse/optional/python-classes/python-classes.ipynb

View source on GitHub

Python Classes & Design#

Object-oriented programming with AI assistance.

Learning Objectives#

  1. Understand when to use classes vs functions

  2. Design class hierarchies

  3. Use AI to generate boilerplate

  4. Apply common design patterns

When to Use Classes#

Use classes when you have:

  • Data + behavior together

  • Multiple instances with same structure

  • State that changes over time

  • Complex initialization

Use functions when:

  • Stateless operations

  • Simple transformations

  • One-off utilities

# Example: OpenAlex Author class
from dataclasses import dataclass, field
from typing import Optional

@dataclass
class Author:
    """Represents an author from OpenAlex."""
    id: str
    name: str
    works_count: int = 0
    cited_by_count: int = 0
    affiliations: list[str] = field(default_factory=list)
    
    @property
    def citations_per_work(self) -> float:
        """Average citations per work."""
        if self.works_count == 0:
            return 0.0
        return self.cited_by_count / self.works_count
    
    @classmethod
    def from_api_response(cls, data: dict) -> 'Author':
        """Create Author from OpenAlex API response."""
        return cls(
            id=data['id'],
            name=data['display_name'],
            works_count=data.get('works_count', 0),
            cited_by_count=data.get('cited_by_count', 0),
        )
# Usage
author = Author(
    id="A123",
    name="Jane Doe",
    works_count=50,
    cited_by_count=1000
)
print(f"{author.name}: {author.citations_per_work:.1f} citations/work")

AI for Class Design#

Let AI handle boilerplate while you focus on design:

> Create a Python class for OpenAlex Work with:
  - id, title, publication_year, cited_by_count, authors (list)
  - Use dataclass
  - Add from_api_response classmethod
  - Add property for age (current year - publication year)
  - Add method to check if highly cited (>100 citations)

Inheritance#

from abc import ABC, abstractmethod

class OpenAlexEntity(ABC):
    """Base class for OpenAlex entities."""
    
    @abstractmethod
    def fetch(self) -> dict:
        """Fetch data from API."""
        pass

class Author(OpenAlexEntity):
    def fetch(self) -> dict:
        # Implementation
        pass

class Work(OpenAlexEntity):
    def fetch(self) -> dict:
        # Implementation
        pass

Common Patterns#

Factory Pattern#

class EntityFactory:
    @staticmethod
    def create(entity_type: str, data: dict):
        if entity_type == 'author':
            return Author.from_api_response(data)
        elif entity_type == 'work':
            return Work.from_api_response(data)

Builder Pattern (for complex objects)#

class QueryBuilder:
    def __init__(self):
        self._filters = []
        self._sort = None
    
    def filter(self, field, value):
        self._filters.append(f"{field}:{value}")
        return self
    
    def sort(self, field, order='asc'):
        self._sort = f"{field}:{order}"
        return self
    
    def build(self) -> str:
        # Build query string
        pass

# Usage
query = (QueryBuilder()
         .filter('year', 2024)
         .filter('type', 'article')
         .sort('cited_by_count', 'desc')
         .build())

Exercise: Design a Scholar API Client#

Design (don’t implement yet) a class structure for:

  • OpenAlexClient - main API client

  • Author, Work, Institution - entity classes

  • SearchResult - wrapper for API responses

Ask AI to help design, but make the architectural decisions yourself.

Summary#

Concept

When to Use

dataclass

Simple data containers

Regular class

Complex behavior

ABC

Define interfaces

Factory

Create objects polymorphically

Builder

Complex construction

Next Steps#

In the next module, we’ll learn GitHub collaboration workflows.

Tips and Tricks#

  • Prompt: “Convert this dictionary-based code to use a dataclass”: AI excels at refactoring data structures into proper classes.

  • Start with dataclasses, not regular classes: Dataclasses give you __init__, __repr__, and __eq__ for free — only use regular classes when you need more control.

  • Prompt: “Add validation to this dataclass using __post_init__”: AI knows the pattern for post-initialization validation.

  • Use ABCs to define interfaces before implementations: Ask the agent: “Create an abstract base class for [concept] with methods [list].”

  • Prompt: “Refactor these functions into a class with shared state”: When you have several functions that pass the same arguments, a class may be cleaner.

  • Favor composition over inheritance: “Create a class that HAS a [component]” produces more flexible designs than deep inheritance chains.

  • Use @property for computed attributes: Prompt: “Add a property that calculates [value] from existing attributes.”

  • Keep classes small: If a class has more than 10 methods, it is probably doing too much — ask AI to suggest how to split it.

Foundational Concepts to Commit to Memory#

  • Dataclasses eliminate boilerplate for classes that primarily hold data — use them when your class is mostly attributes with some computed properties.

  • @property lets you define computed attributes that look like regular attribute access, keeping your interface clean.

  • @classmethod is the standard pattern for alternative constructors (e.g., from_api_response, from_dict, from_file).

  • Abstract Base Classes (ABC) define interfaces — they force subclasses to implement specific methods, catching errors at instantiation rather than at runtime.

  • The Factory pattern creates objects without specifying the exact class, useful when the type depends on input data.

  • The Builder pattern constructs complex objects step by step using method chaining — each method returns self.

  • Composition over inheritance: prefer “has-a” relationships (storing objects as attributes) over deep “is-a” hierarchies. Most real-world code needs at most one level of inheritance.

  • field(default_factory=list) is required for mutable default values in dataclasses — never use a bare [] or {} as a default.

Knowing vs. Doing: Reflection#

Class design is one of those areas where knowing the patterns pays off immediately. If you know that a Factory pattern exists, you can ask an AI agent to implement one in seconds. If you do not know it exists, you will never think to ask — and you will end up writing brittle if/else chains that do the same thing worse. The vocabulary of design patterns is like a map: you do not need to have walked every path, but you need to know the paths exist so you can choose the right one.

At the same time, you could spend a semester studying design patterns and never build anything. The Gang of Four book has 23 patterns. Most working programmers use maybe five regularly. The rest are worth knowing about, not memorizing. AI agents are remarkably good at generating class boilerplate, implementing patterns you describe, and even suggesting which pattern fits your use case. Let the AI handle the syntax; you handle the architecture.

The value you bring is knowing when to use a class at all, which pattern fits the problem, and whether the generated code actually does what you need. That judgment comes from building things, not just reading about them. Build something small with classes this week — even if an AI writes most of the code. You will learn more from reviewing and modifying that code than from reading three more chapters on OOP theory.

Additional Resources#