Class fundamentals

Basic syntax, compared to what you know

Python’s class syntax will look familiar, with a couple of specifics worth calling out:

Try it — edit and run

Two things that differ from Java/C++/C#:

  • self is an explicit first parameter on every instance method — not an implicit keyword like this. You write it yourself in every method signature, and Python passes the instance into it automatically when you call agent.describe().
  • No access modifiers by default — no public/private/protected. Every attribute and method is accessible from outside the class unless you follow a convention (a leading underscore, self._internal) to signal “don’t touch this,” which Python trusts you to respect rather than enforcing.

__init__ and instance attributes

__init__ runs automatically when a class is instantiated — it’s Python’s constructor, though the name itself is just a convention Python recognizes, not a keyword:

Try it — edit and run

__init__’s parameters work exactly like regular function default arguments, including keyword arguments and type hints:

class Agent:
    def __init__(self, name: str, model: str, temperature: float = 0.7):
        self.name = name
        self.model = model
        self.temperature = temperature

(not run live — same behavior as above, just annotated)

Each self.xxx = ... line creates an instance attribute — data that belongs to that specific object, not shared with other instances of the same class:

Try it — edit and run

Methods

A method is just a function defined inside a class, always taking self as its first parameter so it can read and modify that instance’s attributes:

Try it — edit and run

agent.increase_temperature(0.2) — you don’t pass self yourself; Python fills it in automatically as agent because you called the method on agent.

Check your understanding
1/4

Why does every instance method in Python explicitly take self as its first parameter, unlike Java's implicit this?

Exercise · Graded

Implement __init__ with type-hinted parameters (tool_name: str, arguments: dict, result: str = None), storing each as an instance attribute, and implement a method summary(self) -> str that returns "{tool_name}({arguments}) -> {result}", e.g. "search({'query': 'weather'}) -> 3 results found".