Skip to contentSkip to navigation

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 out lives.

  • Class attributes

    A name set in the class body is shared by every object. self.x belongs 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

Tap any part of the code below, or press Next.1 of 5 explored

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.

Python
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)
Output
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.

  1. class Lamp:
  2. rooms = 0
  3. def __init__(self, room, on=False):
  4. self.room = room
  5. self.on = on
  6. Lamp.rooms += 1
  7. hall = Lamp("hall")
  8. desk = Lamp("desk", on=True)
  9. 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 notesOpen

What happens when you create an object

Take a small class:

Try it 1: edit me, then Run
class Player:
    def __init__(self, name, level=1):
        self.name = name
        self.level = level
Output
Press Run to see what it prints.

Player("Mia") does three things:

  1. Python creates a new, empty Player object.
  2. It calls __init__ with that object as self, "Mia" as name, and the default 1 as level.
  3. When __init__ finishes, the new object is the result of the call.

__init__ must not return anything; its only job is to fill in self. People often call it the constructor, although strictly speaking it initialises an object that already exists.

self is just the object

Inside a method, self is a normal variable that refers to the object. self.name = name stores the value as an attribute on that object. The parameter name and the attribute self.name are different things that happen to share a name: the parameter disappears when __init__ ends, the attribute stays with the object. Any method can later read or change it through its own self.

Default values and keyword arguments

__init__ takes arguments just like any function, so everything from the function arguments lesson applies: defaults, keyword arguments and so on.

Try it 2: edit me, then Run
p1 = Player("Mia")                 # level 1
p2 = Player("Leo", level=5)        # keyword argument
print(p1.level, p2.level)          # 1 5
Output
Press Run to see what it prints.

Put the values every object must have first, without defaults, and optional ones afterwards with sensible defaults.

Validating in init

Because every object passes through __init__, it is the perfect place to refuse bad data. Raise an exception, as in the custom exceptions lesson, so an invalid object can never exist:

Try it 3: edit me, then Run
class Temperature:
    def __init__(self, celsius):
        if celsius < -273.15:
            raise ValueError(f"below absolute zero: {celsius}")
        self.celsius = celsius

Temperature(-300)    # ValueError: below absolute zero: -300
Output
Press Run to see what it prints.

You can also tidy values on the way in, such as self.name = name.strip().title(), so the rest of the class can trust them.

Instance attributes and class attributes

Attributes set through self belong to one object: these are instance attributes. Variables written directly in the class body belong to the class itself and are shared by every object: these are class attributes.

Try it 4: edit me, then Run
class Ticket:
    price = 12                      # class attribute: shared
    def __init__(self, seat):
        self.seat = seat            # instance attribute: one per object

a = Ticket("A1")
b = Ticket("B7")
print(a.price, b.price)             # 12 12
Ticket.price = 15
print(a.price, b.price)             # 15 15
Output
Press Run to see what it prints.

When you read a.price, Python first looks on the object a. If it is not there, it looks on the class. That is why changing Ticket.price changes what every ticket sees. Class attributes suit constants and settings shared by all objects, such as a tax rate or the maximum level.

Be careful when assigning through an object: a.price = 20 does not change the class. It creates a new instance attribute on a that hides the class attribute for a only, while b still sees 15.

The shared list trap

A class attribute that holds a list is shared by everyone, which is almost never what you want:

Try it 5: edit me, then Run
class Team:
    members = []                    # one list for ALL teams
    def add(self, name):
        self.members.append(name)

red, blue = Team(), Team()
red.add("Ana")
print(blue.members)                 # ['Ana'], blue did not want her
Output
Press Run to see what it prints.

The same thing happens with a list as a default argument, def __init__(self, members=[]), because the default list is created once when the function is defined and reused for every call. The fix in both cases is to create a fresh list inside __init__:

Try it 6: edit me, then Run
class Team:
    def __init__(self, members=None):
        self.members = [] if members is None else list(members)
Output
Press Run to see what it prints.

Making objects print nicely

Printing an object shows its string form. By default that is something like <__main__.Player object at 0x7f...>. Two special methods let you choose better text:

Try it 7: edit me, then Run
class Player:
    def __init__(self, name, level=1):
        self.name = name
        self.level = level

    def __str__(self):
        return f"{self.name} (level {self.level})"

    def __repr__(self):
        return f"Player({self.name!r}, {self.level})"

mia = Player("Mia", 4)
print(mia)          # Mia (level 4)
print([mia])        # [Player('Mia', 4)]
Output
Press Run to see what it prints.

__str__ is for people: print and str() use it. __repr__ is for programmers: the shell, debuggers and containers such as lists use it, and a good __repr__ looks like the code that would recreate the object. If you only write one, write __repr__; Python falls back to it when there is no __str__.

Attributes for internal use

A name starting with one underscore, such as self._cache, is a signal to other programmers: "this is internal; use the methods instead". Python does not enforce it, but everyone respects the convention. The Python in Depth course shows properties, which control how attributes are read and set.

Syntax

The general shape of the statements in this lesson.

syntax.py
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})"
Output
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

Beginner

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.

Python
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)
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

Every booking passes through __init__, so names are always tidy and a booking for 12 can never exist. print(booking) uses __str__, while printing the list uses each object's __repr__. The limit lives in one class attribute, shared by all bookings.

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.

Buggy code: run it
class Cart:
    items = []
    def add(self, item):
        self.items.append(item)

a, b = Cart(), Cart()
a.add('pen')
print(b.items)
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints ['pen'], although b never added anything

Write this instead

class Cart:
    def __init__(self):
        self.items = []
    def add(self, item):
        self.items.append(item)

Why it happens

items is a class attribute, so both carts append to the same single list.

In the real world

Where this shows up in software people use every day.

  1. Sensor readings with units

    Environmental monitoring

    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.

    Python
    class 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()])
    Output
    Press 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__?

No; a second def __init__ replaces the first. Use default and keyword arguments to support different ways of creating an object.

Why does printing a list of my objects ignore __str__?

Containers show their items with repr, not str. Define __repr__ as well, or instead.

Can one object hold other objects?

Yes, and it is very common. A Team can keep a list of Player objects, and an Order a list of Item objects. Each attribute can be any value at all, including objects of your own classes.

Should every attribute be set in __init__?

Yes, as a habit. Even attributes that start empty, such as self.items = [] or self.result = None, belong there, so readers can see the full shape of the object.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

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.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

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.