A420 of 56
0 XP
  1. Hook
  2. Predict
  3. Name it
  4. Check
  5. Explain

A4 · Lesson 20 · Classes and objects

A resistor that knows its own tolerance

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)

Name it

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 Resistors 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.

Worked example

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

Show the 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.

Worked example

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

Show the 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

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 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

Add a power(self, V) method returning V2/R. For the starter's list of resistors, set hottest to the one that dissipates the most at V = 12 V, and P to that power.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

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

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

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 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

Write a class RC whose __init__(self, R, C) stores the two values, with methods tau() returning RC, corner() returning 1/(2πRC) in hertz, and gain(f) returning 1/1+(f/fc)2. Then set lp = RC(R, C) for R = 4700 Ω and C = 2.2 × 10⁻⁹ F, and g = lp.gain(f) at f = 1000 Hz.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

What does this print?

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

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

Explain why

What does self mean inside a method, and why does every method need it?

Practice

Keep practicing

7 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.