---
title: Classes and objects
heading: A resistor that knows its own tolerance
eyebrow: A4 · Lesson 20 · Classes and objects
xp: 40
---

::: hook
A resistor in a design isn't just a number. It has a value, a tolerance, a power rating and a temperature coefficient, and you keep asking the same questions of it: what's its worst-case value, how hot will it get? A **class** bundles that data with the functions that answer those questions, so each resistor in your script carries everything about itself. The NumPy arrays, matplotlib figures and complex numbers you've already used are all objects made from classes.
:::

::: predict
## After the code below, what is `r.value`?

```
class Part:
    def __init__(self, value):
        self.value = value

r = Part(4700)
```

- [x] 4700
- [ ] `None`
- [ ] `Part`
- [ ] An error, since `__init__` returns nothing

::: reveal
4700. Calling `Part(4700)` makes a new **object** and runs `__init__` on it, with `self` standing for that object. `self.value = value` stores 4700 on it as an **attribute**, which you read later as `r.value`.
:::
:::

::: nameit
## Defining a class

```
class Resistor:
    """A resistor with a nominal value in ohms and a tolerance as a fraction."""

    def __init__(self, value, tol=0.05):
        self.value = value
        self.tol = tol

    def bounds(self):
        return self.value * (1 - self.tol), self.value * (1 + self.tol)

    def power(self, V):
        return V**2 / self.value

    def __repr__(self):
        return f"Resistor({self.value:g}, {self.tol:.0%})"
```

- `class Resistor:` defines the type; by convention class names are capitalized.
- **Methods** are functions defined inside it. Their first argument, `self`, is the object they're called on: `r.bounds()` runs `bounds` with `self` set to `r`.
- `__init__` runs when an object is made and sets up its **attributes**.
- `__repr__` says how the object prints, which makes debugging far easier.

```
r = Resistor(4700, 0.01)
r.bounds()        # (4653.0, 4747.0)
r.power(12)       # 0.0306...
print(r)          # Resistor(4700, 1%)
```

## Why bother?

- **Data and behavior stay together.** A list of `Resistor`s carries every tolerance with its value, so a worst-case calculation can't pair the wrong ones.
- **Many objects, one definition.** Each resistor has its own attributes; the methods are written once.
- **Readable code.** `r.bounds()` says what it means.

Classes can do much more (inheritance, operator overloading such as making `r1 + r2` mean series), but a small class with an `__init__`, a few methods and a `__repr__` covers most engineering scripts.
:::

::: example
## Find the worst-case range of a divider's output using Resistor objects.

::: solution
1. **Take each resistor's bounds.** The objects carry their own tolerances, so the function needs no extra arguments.
2. **Pair the extremes.** The output is lowest with the top resistor high and the bottom low, and highest the other way round.

```
def divider_range(Vs, top, bottom):
    t_lo, t_hi = top.bounds()
    b_lo, b_hi = bottom.bounds()
    lo = Vs * b_lo / (t_hi + b_lo)
    hi = Vs * b_hi / (t_lo + b_hi)
    return lo, hi

print(divider_range(12, Resistor(10e3, 0.05), Resistor(10e3, 0.05)))
# (5.7, 6.3)
```

**Answer:** with 12 V across two 10 kΩ 5% resistors, the output ranges from 5.7 V to 6.3 V.
:::
:::

::: example
## Make a list of parts and find the one that dissipates the most at 5 V.

::: solution
1. **Make the list of parts.** Three `Resistor` objects.
2. **Take the largest by power.** `max` with a key works on objects just as on numbers: the key calls a method.

```
parts = [Resistor(100), Resistor(220), Resistor(47)]
hottest = max(parts, key=lambda r: r.power(5))
print(hottest, hottest.power(5))      # Resistor(47, 5%) 0.531...
```

**Answer:** the 47 Ω resistor dissipates the most at 5 V, 0.531 W.
:::
:::

::: check
kind: python
given: R = 1k..100k E12; t = 1 | 5 | 10

## Write a class `Resistor` whose `__init__(self, value, tol=0.05)` stores `value` and `tol`, and whose `bounds()` returns `(low, high)`. Set `r = Resistor(R, t / 100)` and `lo, hi = r.bounds()`.

```python starter
class Resistor:
    def __init__(self, value, tol=0.05):
        pass

r = Resistor(R, t / 100)
lo, hi = 0, 0
print(lo, hi)
```

```python solution
class Resistor:
    def __init__(self, value, tol=0.05):
        self.value = value
        self.tol = tol

    def bounds(self):
        return self.value * (1 - self.tol), self.value * (1 + self.tol)

r = Resistor(R, t / 100)
lo, hi = r.bounds()
print(lo, hi)
```

```python tests
import math
x = Resistor(1000)
assert x.value == 1000 and x.tol == 0.05, "__init__ should store value and tol on self, with tol defaulting to 0.05."
a, b = Resistor(1000, 0.1).bounds()
assert math.isclose(a, 900) and math.isclose(b, 1100), "bounds() of a 1 kΩ, 10% resistor should be (900, 1100)."
assert math.isclose(lo, R * (1 - t / 100)) and math.isclose(hi, R * (1 + t / 100)), "lo and hi don't match for this lab's resistor."
```

::: right
Right. `self.value` and `self.tol` belong to each object, and `bounds` reads them.
:::
:::

::: check
kind: python
given: V = 5 | 12 | 24; k = 0..3 int

## Add a `power(self, V)` method returning $V^2/R$. For the starter's list of resistors, set `hottest` to the one that dissipates the most at `V` = {V} V, and `P` to that power.

```python starter
class Resistor:
    def __init__(self, value, tol=0.05):
        self.value = value
        self.tol = tol

parts = [Resistor(v) for v in [[100, 220, 47], [1000, 330, 680], [10, 22, 15, 33], [4700, 2200, 1000]][k]]
hottest = parts[0]
P = 0
print(hottest.value, P)
```

```python solution
class Resistor:
    def __init__(self, value, tol=0.05):
        self.value = value
        self.tol = tol

    def power(self, V):
        return V**2 / self.value

parts = [Resistor(v) for v in [[100, 220, 47], [1000, 330, 680], [10, 22, 15, 33], [4700, 2200, 1000]][k]]
hottest = max(parts, key=lambda r: r.power(V))
P = hottest.power(V)
print(hottest.value, P)
```

```python tests
import math
vals = [[100, 220, 47], [1000, 330, 680], [10, 22, 15, 33], [4700, 2200, 1000]][k]
assert math.isclose(Resistor(100).power(10), 1), "Resistor(100).power(10) should be 1 W."
assert hottest.value == min(vals), "The smallest resistor dissipates the most at a fixed voltage."
assert math.isclose(P, V**2 / min(vals)), "P should be the hottest resistor's power."
```

::: right
Right. A method is called on the object, and `max` with a key compares objects by any method you like.
:::
:::

::: check
kind: python
given: R = 4700 | 100000 | 33; t = 1 | 5

## Give `Resistor` a `__repr__` so that `print(Resistor(4700, 0.01))` shows `Resistor(4700, 1%)`. Set `s = repr(Resistor(R, t / 100))`.

```python starter
class Resistor:
    def __init__(self, value, tol=0.05):
        self.value = value
        self.tol = tol

s = repr(Resistor(R, t / 100))
print(s)
```

```python solution
class Resistor:
    def __init__(self, value, tol=0.05):
        self.value = value
        self.tol = tol

    def __repr__(self):
        return f"Resistor({self.value:g}, {self.tol:.0%})"

s = repr(Resistor(R, t / 100))
print(s)
```

```python tests
assert repr(Resistor(4700, 0.01)) == "Resistor(4700, 1%)", f'repr(Resistor(4700, 0.01)) should be "Resistor(4700, 1%)", but it is {repr(Resistor(4700, 0.01))!r}. Try the format specs :g and :.0%.'
assert repr(Resistor(33, 0.05)) == "Resistor(33, 5%)", 'repr(Resistor(33, 0.05)) should be "Resistor(33, 5%)".'
```

::: right
Right. `:g` drops the trailing `.0` and `:.0%` turns 0.01 into `1%`.
:::
:::

::: check
kind: python
given: Vs = 5 | 12; t = 1 | 5 | 10

## Using the `Resistor` class with `bounds()`, write `divider_range(Vs, top, bottom)` returning the lowest and highest possible output. Set `lo, hi = divider_range(Vs, Resistor(10e3, t / 100), Resistor(10e3, t / 100))`.

```python starter
class Resistor:
    def __init__(self, value, tol=0.05):
        self.value = value
        self.tol = tol

    def bounds(self):
        return self.value * (1 - self.tol), self.value * (1 + self.tol)

def divider_range(Vs, top, bottom):
    v = Vs * bottom.value / (top.value + bottom.value)
    return v, v

lo, hi = divider_range(Vs, Resistor(10e3, t / 100), Resistor(10e3, t / 100))
print(lo, hi)
```

```python solution
class Resistor:
    def __init__(self, value, tol=0.05):
        self.value = value
        self.tol = tol

    def bounds(self):
        return self.value * (1 - self.tol), self.value * (1 + self.tol)

def divider_range(Vs, top, bottom):
    t_lo, t_hi = top.bounds()
    b_lo, b_hi = bottom.bounds()
    return Vs * b_lo / (t_hi + b_lo), Vs * b_hi / (t_lo + b_hi)

lo, hi = divider_range(Vs, Resistor(10e3, t / 100), Resistor(10e3, t / 100))
print(lo, hi)
```

```python tests
import math
f = t / 100
assert math.isclose(lo, Vs * (1 - f) / 2), "The lowest output has the top resistor high and the bottom one low."
assert math.isclose(hi, Vs * (1 + f) / 2), "The highest output has the top resistor low and the bottom one high."
```

::: right
Right. Each extreme pairs one resistor's high bound with the other's low bound.
:::
:::

::: check
kind: python
given: R = 1k..100k E12; C = 1n..1u E6; f = 10 | 100 | 1000 | 10000

## Write a class `RC` whose `__init__(self, R, C)` stores the two values, with methods `tau()` returning $RC$, `corner()` returning $1/(2\pi RC)$ in hertz, and `gain(f)` returning $1/\sqrt{1 + (f/f_c)^2}$. Then set `lp = RC(R, C)` for `R` = {R} Ω and `C` = {C} F, and `g = lp.gain(f)` at `f` = {f} Hz.

```python starter
import math

class RC:
    def __init__(self, R, C):
        pass

lp = RC(R, C)
g = 0
print(g)
```

```python solution
import math

class RC:
    def __init__(self, R, C):
        self.R = R
        self.C = C

    def tau(self):
        return self.R * self.C

    def corner(self):
        return 1 / (2 * math.pi * self.tau())

    def gain(self, f):
        return 1 / math.sqrt(1 + (f / self.corner())**2)

lp = RC(R, C)
g = lp.gain(f)
print(g)
```

```python tests
import math
fc = 1 / (2 * math.pi * R * C)
assert abs(lp.tau() - R * C) < 1e-15, "tau() returns self.R * self.C."
assert abs(lp.corner() - fc) < 1e-9 * fc, "corner() is 1 / (2π RC)."
assert abs(g - 1 / math.sqrt(1 + (f / fc)**2)) < 1e-12, "gain(f) is 1 / sqrt(1 + (f/fc)**2)."
assert abs(RC(1e3, 1e-6).gain(1 / (2 * math.pi * 1e-3)) - 1 / math.sqrt(2)) < 1e-12, "At the corner the gain should be 1/√2."
```

::: right
Right. The object carries its R and C, and each method builds on the one before: `corner` uses `tau`, and `gain` uses `corner`. Change a value once and every result follows.
:::
:::

::: check
kind: choice

## What does this print?

```python
class Part:
    count = 0
    def __init__(self):
        Part.count += 1

a = Part()
b = Part()
print(Part.count)
```

- [x] `2`
- [ ] `0`
- [ ] `1`
- [ ] An error

::: right
Right. `count` belongs to the class, shared by every object, and each `__init__` adds one to it. Two objects were made, so it's 2.
:::

::: misses
- [2] `__init__` runs every time an object is made, and each run adds one to `Part.count`.
- [3] `count` lives on the class, not on each object, so both calls add to the same number.
- [4] Changing a class attribute through the class name is allowed.
:::
:::

::: explain
## What does `self` mean inside a method, and why does every method need it?

::: model
`self` is the particular object the method was called on. When you write `r.bounds()`, Python runs `bounds` with `self` set to `r`, so `self.value` is that resistor's value and not some other one's. Every method needs it because the same method code is shared by all the objects of the class, and `self` is how the code knows which object's attributes to use.
:::
:::

::: practice

::: check
kind: python
given: v = 1 | 10 | 47; c = 1e-9 | 1e-7

## Write a class `RC` with attributes `R` and `C` and a method `tau()` returning `R * C`. Set `t = RC(v * 1000, c).tau()`.

```python starter
class RC:
    pass

t = 0
print(t)
```

```python solution
class RC:
    def __init__(self, R, C):
        self.R = R
        self.C = C

    def tau(self):
        return self.R * self.C

t = RC(v * 1000, c).tau()
print(t)
```

```python tests
import math
assert math.isclose(RC(1000, 1e-6).tau(), 1e-3), "RC(1000, 1e-6).tau() should be 0.001 s."
assert math.isclose(t, v * 1000 * c), "t doesn't match."
```
:::

::: check
kind: python
given: n = 2..6 int

## Make a list of `n` = {n} `Part` objects with values 100, 200, ..., and set `total` to the sum of their `value` attributes.

```python starter
class Part:
    def __init__(self, value):
        self.value = value

parts = []
total = 0
print(total)
```

```python solution
class Part:
    def __init__(self, value):
        self.value = value

parts = [Part(100 * (k + 1)) for k in range(n)]
total = sum(p.value for p in parts)
print(total)
```

```python tests
assert len(parts) == n and all(isinstance(p, Part) for p in parts), "parts should hold n Part objects."
assert total == 100 * n * (n + 1) // 2, "total should be the sum of the values."
```
:::
:::
