Table of Contents


Motivation: why Python classes?

Before introducing classes, consider a common pattern that does not scale well: keeping state in global variables and passing it through functions manually.

Version 1 — Passing state as a parameter

def test_login(username, counter):
    if username != 'fulano':
        return counter + 1
 
counter = 0
counter = test_login('sicrano', counter)
print(counter)
counter = test_login('beltrano', counter)
print(counter)

Output:

1
2

Observation

The caller is responsible for carrying the counter state around. Every new function that touches it needs the parameter threaded through.

Version 2 — Using a global variable

counter = 10
 
def test_login(username):
    global counter
    if username != 'fulano':
        counter = counter + 1
        return counter
 
test_login('sicrano')
print(counter)

Output:

11

Anti-pattern

global state is fragile: any function can mutate it, order of calls matters, and refactoring becomes risky. Avoid global in production code.

Version 3 — State shared between two functions

counter = 20
 
def test_login(username):
    global counter
    if username != 'fulano':
        counter = counter + 1
        return counter
 
def show_counter():
    global counter
    counter = counter - 1
    print(counter)
 
test_login('sicrano')
show_counter()

Output:

20

Takeaway

State (counter) and behaviour (test_login, show_counter) are scattered. A class bundles both together — that is the motivation for the next section.

Classes

The Celsius class encapsulates a temperature value and validates it on assignment.

class Celsius:
    """Works with temperatures."""
 
    def __init__(self, temperature):
        self.temperature = temperature
 
    def get_temperature(self):
        return self.temperature
 
    def set_temperature(self, temperature):
        if type(temperature) != float:
            raise TypeError('Must be float')
        if temperature < -273.15:
            raise ValueError('temperature below 0K')
        else:
            self.temperature = temperature

Instantiating and reading

casa_das_caldas = Celsius(24.9)
casa_das_caldas.get_temperature()

Output:

24.9

Validation in action

try:
    casa_das_caldas.set_temperature(-1000)
except ValueError as ex:
    print(f'ERROR: {ex}')
casa_das_caldas.get_temperature()

Output:

ERROR: temperature below 0K
24.9
try:
    casa_das_caldas.set_temperature('abc')
except TypeError as ex:
    print(ex)

Output:

Must be float

Java-style getters/setters

This get_/set_ pattern works, but Python has a more idiomatic mechanism — the @property decorator — shown in the next section.

The encapsulation problem

Instances store their attributes in the instance dictionary, which is writable by anyone:

casa_das_caldas.__dict__

Output:

{'temperature': 24.9}
casa_das_caldas.humidity = 68.4
casa_das_caldas.__dict__

Output:

{'temperature': 24.9, 'humidity': 68.4}

Nothing prevents direct assignment that bypasses validation entirely:

casa_das_caldas.temperature = 'Tia anita do Loulé..'
casa_das_caldas.__dict__

Output:

{'temperature': 'Tia anita do Loulé..', 'humidity': 68.4}

Broken invariant

The attribute now holds a string. Direct attribute assignment skipped set_temperature, so the “temperature is a float above absolute zero” rule is gone. Properties fix this.

Improved Celsius class with the @property decorator

By convention, a single leading underscore (_temperature) marks the attribute as internal. The @property decorator turns a method into a read-only attribute; the paired @temperature.setter intercepts assignments so validation always runs.

class Celsius:
 
    def __init__(self, temperature=0):
        self._temperature = temperature
 
    @property
    def temperature(self):
        return self._temperature
 
    @temperature.setter
    def temperature(self, temperature):
        if type(temperature) != float:
            raise TypeError('Must be float')
        if temperature < -273.15:
            raise ValueError('temperature below 0K')
        else:
            self._temperature = temperature
 
    def to_fahrenheit(self):
        return self._temperature * 1.8 + 32
 
    def __str__(self):
        return f'{self._temperature}\u2103'  # ºC
 
    def __repr__(self):
        return f'{self._temperature=}'

Default value and internal storage

room3 = Celsius()
room3.__dict__

Output:

{'_temperature': 0}

Dunder methods

__str__ defines what print() shows; __repr__ defines what the interactive interpreter (and notebooks) display when the object is evaluated.

Assignment now goes through the setter

room3.temperature = 24.6
room3.temperature

Output:

24.6

__repr__ in the interpreter

room3

Output:

self._temperature=24.6

Extra behaviour method

print(room3.to_fahrenheit())

Output:

32.0

Exercise 1 - Improve Celsius class

  • Allow to use class with int and string (converted to int or float)
  • Allow to convert to Rankine
  • Allow input via Fahrenheit as classmethod
class Celsius:
    """Works with temperatures."""
 
    ABSOLUTE_ZERO = -273.15
 
    def __init__(self, temperature=0.0):
        self.temperature = temperature  # goes through the setter
 
    @property
    def temperature(self):
        return self._temperature
 
    @temperature.setter
    def temperature(self, temperature):
        # bool is a subclass of int, so reject it explicitly
        if isinstance(temperature, bool):
            raise TypeError('Temperature must be int, float or numeric string')
 
        if isinstance(temperature, str):
            try:
                temperature = float(temperature.strip())  # "25" -> 25.0
            except ValueError:
                raise ValueError(f'Cannot convert {temperature!r} to a number')
        elif isinstance(temperature, (int, float)):
            temperature = float(temperature)
        else:
            raise TypeError('Temperature must be int, float or numeric string')
 
        if temperature < self.ABSOLUTE_ZERO:
            raise ValueError('Temperature below absolute zero (0 K)')
 
        self._temperature = temperature
 
    def to_fahrenheit(self, digits=2):
        return round(self._temperature * 1.8 + 32, digits)
 
    def to_rankine(self, digits=2):
        return round((self._temperature - self.ABSOLUTE_ZERO) * 1.8, digits)
 
    @classmethod
    def from_fahrenheit(cls, temperature, digits=2):
        """Alternative constructor: build a Celsius object from Fahrenheit."""
        return cls(round((float(temperature) - 32) / 1.8, digits))
 
    def __str__(self):
        return f'{self._temperature}\u2103'
 
    def __repr__(self):
        return f'Celsius({self._temperature})'

Usage

Celsius(25)                    # int    -> 25.0
Celsius("36.6")                # str    -> 36.6
Celsius(100).to_fahrenheit()   # 212.0
Celsius(0).to_rankine()        # 491.67
Celsius.from_fahrenheit(212)   # 100.0℃
Celsius.from_fahrenheit("98.6")  # 37.0℃
Celsius("abc")                 # ValueError
Celsius(-300)                  # ValueError (below 0 K)

Exercise: Conversion rates

Design a CurrencyRates class that fetches the latest exchange rates from the
Frankfurter API and converts any supported currency
into EUR.

Resources

Sample response (GET https://api.frankfurter.dev/v2/rates) — a JSON array
of quote records:

[
  { "date": "2026-11-05", "base": "EUR", "quote": "USD", "rate": 1.1247 },
  { "date": "2026-11-05", "base": "EUR", "quote": "GBP", "rate": 0.8347 },
  { "date": "2026-11-05", "base": "EUR", "quote": "JPY", "rate": 178.06 }
]

Requirements

#RequirementHint
1Convert any supported quote into EUR (and EUR → quote) vs. division
2List all possible currenciesexpose the dictionary keys
3Show the rate dateone attribute, read-only
4Store rates in an internal dictionaryone HTTP call per instance; avoids API rate limits
5Invalid currency must raise ValueErrorvalidate before dividing

Design constraints

  • Rates are read from the API once, at instantiation, and kept in memory.
  • The internal dictionary must not be exposed directly — use methods or
    properties, applying the encapsulation patterns from this module.

Solution: Conversion rates

Step 0 — Explore the API from the shell

Before writing the class, inspect the payload shape:

curl -s https://api.frankfurter.dev/v2/rates | python3 -m json.tool | head -20

Expected: a JSON array of records, each with date, base, quote and
rate. Knowing this drives every design decision below.

Step 1 — Fetch once, store in a dictionary

import urllib.request
import json
 
class CurrencyRates:
    _URL = "https://api.frankfurter.dev/v2/rates"
 
    def __init__(self):
        with urllib.request.urlopen(self._URL) as response:
            records = json.load(response)
        self._rates = {r["quote"]: r["rate"] for r in records}
        self._date = records[0]["date"]

Why this shape

  • Comprehension as the constructor’s core. {r["quote"]: r["rate"] for ...}
    turns a list of records into a dictionary — O(1) lookups, no repeated API
    calls. This is exactly how the Celsius class in this module stored state
    internally (self._temperature).
  • _ prefix = encapsulation. _rates and _date signal “internal state,
    do not touch from outside” — the same convention used for
    Celsius._temperature.
  • Class constant _URL. Configuration lives at class level, not buried in
    method bodies; it can be overridden in tests later.
  • Standard library only. urllib.request avoids external dependencies for a
    classroom exercise; requests is the production choice.

Step 2 — Read-only properties for metadata

    @property
    def currencies(self):
        """All supported quote currencies (read-only view)."""
        return tuple(self._rates)  # or sorted(...)
 
    @property
    def rate_date(self):
        """Date of the fetched rates."""
        return self._date

Why this shape

  • @property turns methods into read-only attributes. rates.date works
    without parentheses, and writing rates.date = "..." raises
    AttributeError — mirroring the setter-less property pattern from the
    Celsius class.
  • tuple(self._rates) returns a copy, so callers cannot mutate the internal
    dictionary through the exposed view. Returning self._rates.keys() directly
    would stay live-bound to the internal state.

Step 3 — Conversions: two directions

The API gives one EUR unit expressed in each quote currency
(1 EUR = 1.1247 USD). Both directions come from that single number:

ConversionFormula
quote → EUR
EUR → quote
    def to_eur(self, amount, quote):
        """Convert an amount in `quote` currency into EUR."""
        try:
            rate = self._rates[quote.upper()]
        except KeyError:
            raise ValueError(f"Unknown currency: {quote!r}")
        return round(amount / rate, 2)
 
    def from_eur(self, amount, quote):
        """Convert a EUR amount into `quote` currency."""
        try:
            rate = self._rates[quote.upper()]
        except KeyError:
            raise ValueError(f"Unknown currency: {quote!r}")
        return round(amount * rate, 2)

Why this shape

  • Look before dividing. A direct self._rates[quote] would raise a
    KeyError — meaningful only to Python programmers. Catching it and raising
    ValueError gives callers a domain error, consistent with how
    Celsius raises ValueError for temperatures below absolute zero.
  • .upper() normalization accepts "usd", "Usd" and "USD" alike.
  • round(..., 2) mirrors the digits=2 convention already used in
    Celsius.to_fahrenheit.

Step 4 — DRY: factor the duplicated validation

Steps 3 repeats the try/except twice — a smell. Extract one helper:

    def _get_rate(self, quote):
        try:
            return self._rates[quote.upper()]
        except KeyError:
            raise ValueError(f"Unknown currency: {quote!r}")
 
    def to_eur(self, amount, quote):
        return round(amount / self._get_rate(quote), 2)
 
    def from_eur(self, amount, quote):
        return round(amount * self._get_rate(quote), 2)

Why this shape

  • Single source of truth for validation; adding a rule later (e.g. rejecting
    crypto quotes) touches one method.
  • The _get_rate prefix marks it as an internal helper, not part of the public
    API.

Step 5 — Nice output with __repr__

    def __repr__(self):
        n = len(self._rates)
        return f"CurrencyRates({n} quotes, {self._date})"

Why this shape

  • Follows the module’s Celsius.__repr__ convention: short, unambiguous, and
    developer-oriented (__str__ would be the user-facing variant).

Step 6 — Complete class and usage

import urllib.request
import json
 
class CurrencyRates:
    """EUR-based exchange rates fetched once from the Frankfurter API."""
 
    _URL = "https://api.frankfurter.dev/v2/rates"
 
    def __init__(self):
        with urllib.request.urlopen(self._URL) as response:
            records = json.load(response)
        self._rates = {r["quote"]: r["rate"] for r in records}
        self._date = records[0]["date"]
 
    def _get_rate(self, quote):
        try:
            return self._rates[quote.upper()]
        except KeyError:
            raise ValueError(f"Unknown currency: {quote!r}")
 
    def to_eur(self, amount, quote):
        """Convert an amount in `quote` currency into EUR."""
        return round(amount / self._get_rate(quote), 2)
 
    def from_eur(self, amount, quote):
        """Convert a EUR amount into `quote` currency."""
        return round(amount * self._get_rate(quote), 2)
 
    @property
    def currencies(self):
        """All supported quote currencies (read-only view)."""
        return tuple(self._rates)
 
    @property
    def rate_date(self):
        """Date of the fetched rates."""
        return self._date
 
    def __repr__(self):
        n = len(self._rates)
        return f"CurrencyRates({n} quotes, {self._date})"

Usage

rates = CurrencyRates()          # one HTTP call, everything cached
rates                            # CurrencyRates(160 quotes, 2026-11-05)
rates.rate_date                  # '2026-11-05'
"USD" in rates.currencies        # True
 
rates.from_eur(100, "USD")       # 112.47   EUR -> USD
rates.to_eur(112.47, "USD")      # 100.0    USD -> EUR
rates.from_eur(100, "jpy")       # 17806.0  case-insensitive
 
rates.to_eur(1, "BTC")           # ValueError: Unknown currency ... (if absent)
rates.rate_date = "2020-01-01"   # AttributeError: read-only property

Checkpoint — self-review questions

  1. How many HTTP calls does creating three CurrencyRates instances make?
    How could you make it one? (Hint: class-level cache or a shared instance.)
  2. Why does currencies return a tuple instead of the raw dictionary?
  3. What error does the Celsius class raise for bad input, and what does
    CurrencyRates raise? Are they consistent? Why does that matter?
  4. Stretch: add convert(amount, source, target) for arbitrary currency-pair
    conversion — what is the formula when neither side is EUR?