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)
- Calling
Part(4700)makes a new object and runs__init__on it, withselfstanding for that object.self.value = valuestores 4700 on it as an attribute, which you read later asr.value.
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()runsboundswithselfset tor. __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
- Take each resistor's bounds. The objects carry their own tolerances, so the function needs no extra arguments.
- 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
- Make the list of parts. Three
Resistorobjects. - Take the largest by power.
maxwith 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 . 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 , corner() returning in hertz, and gain(f) returning . 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?
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
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.