Module 10 · Lesson 02
Constructors, self and Attributes
Set objects up properly: give __init__ defaults and validation, tell instance attributes from class attributes, avoid the shared-list trap, and make objects print nicely with __str__ and __repr__.
- About 8 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- Defaults in __init__
- Shared or own attributes
- Print objects nicely
- Watch two lamps get built
Setting up new objects
`__init__` runs once for each new object and gives it a good starting state.
__init__
Runs as soon as you call the class. It sets the object's attributes and returns nothing.
Defaults
def __init__(self, name, lives=3):lets callers leave outlives.Class attributes
A name set in the class body is shared by every object.
self.xbelongs to one object.__str__ and __repr__
Tell Python what to show when you
print()an object or see it inside a list.
Good setup everywhere
Every new thing in an app starts from a sensible state.
- New playersEvery new player starts with 3 lives and 0 points.
- AccountsA new account checks its email has an @ before it is created.
- RecipesA recipe prints as "Pancakes (20 min)" instead of a memory address.
- PlaylistsEach new playlist gets its own empty song list.
The first line of __init__
This line decides what a new object needs. Tap each part to see its job.
Part 1 of 5
def:A method is defined like any function.
Set objects up well
Pick an example, change it, then press Run. Say what you expect to see before you press.
Example 1 of 6Defaults
A default fills in a value the caller left out.
Your turn: Add a level attribute that always starts at 1.
class Player:
def __init__(self, name, lives=3):
self.name = name
self.lives = lives
self.score = 0
ana = Player("Ana")
ben = Player("Ben", lives=5)
print(ana.name, ana.lives, ana.score)
print(ben.name, ben.lives, ben.score)Press Run to see what it prints.Watch two lamps get built
Press Step to run one line at a time. `Lamp.rooms` lives on the class; `self.on` lives on one lamp.
Ready. Press Step to run the first line.
- class Lamp:
- rooms = 0
- def __init__(self, room, on=False):
- self.room = room
- self.on = on
- Lamp.rooms += 1
- hall = Lamp("hall")
- desk = Lamp("desk", on=True)
- print(hall.on, desk.on, Lamp.rooms)
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.When is the default used?
class Order:
def __init__(self, item, qty=1):
self.item = item
self.qty = qty
print(Order("tea").qty, Order("cake", 3).qty)0 of 6 answered
Common __init__ misconceptions
Each card is something learners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
class Player:
max_level = 99 # class attribute (shared)
def __init__(self, name, level=1): # defaults like any function
if level < 1:
raise ValueError("level must be at least 1")
self.name = name # instance attribute
self.level = level
self.items = [] # fresh list per object
def __str__(self): # print(obj), str(obj)
return f"{self.name} ({self.level})"
def __repr__(self): # debugging, inside lists
return f"Player({self.name!r}, {self.level})"Press Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
A validated booking
Model a restaurant booking that tidies the guest's name, defaults to 2 people, refuses group sizes outside 1 to 8, and prints as a readable line.
class Booking:
max_guests = 8
def __init__(self, name, guests=2, time="19:00"):
if not 1 <= guests <= Booking.max_guests:
raise ValueError(f"guests must be 1 to {Booking.max_guests}, got {guests}")
self.name = name.strip().title()
self.guests = guests
self.time = time
def __str__(self):
return f"{self.time} {self.name}, table for {self.guests}"
def __repr__(self):
return f"Booking({self.name!r}, {self.guests}, {self.time!r})"
tonight = [Booking(" ana lopez"), Booking("ben", 5, "20:30")]
for booking in tonight:
print(booking)
print(tonight)
try:
Booking("cy", 12)
except ValueError as error:
print("Refused:", error)Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
A list shared by every object
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
class Cart:
items = []
def add(self, item):
self.items.append(item)
a, b = Cart(), Cart()
a.add('pen')
print(b.items)Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Environmental monitoring
Sensor readings with units
A city network of air sensors sends readings that must never be negative and must state where they were taken. Engineers inspect lists of readings all day, so each reading prints clearly.
Why Python fits
Validation in
__init__means a broken sensor's negative value is rejected at the door. The unit is a class attribute because every reading shares it.__str__gives the engineers' view, and__repr__makes the filtered list readable.Pythonclass Reading: unit = "ug/m3" def __init__(self, sensor, value): if value < 0: raise ValueError(f"{sensor}: negative reading {value}") self.sensor = sensor self.value = round(value, 1) def is_high(self, limit=25): return self.value > limit def __str__(self): return f"{self.sensor}: {self.value} {Reading.unit}" def __repr__(self): return f"Reading({self.sensor!r}, {self.value})" raw = [("park", 12.34), ("bridge", 31.0), ("school", -2), ("market", 26.66)] readings = [] for sensor, value in raw: try: readings.append(Reading(sensor, value)) except ValueError as error: print("Rejected", error) for r in readings: print(r, "HIGH" if r.is_high() else "ok") print([r for r in readings if r.is_high()])OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
Can a class have more than one __init__?
Why does printing a list of my objects ignore __str__?
Can one object hold other objects?
Should every attribute be set in __init__?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 12 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.