Skip to content
skillbld
Day 12 of 14 35 minclass__init__Methods

Model real things in code. Define classes, create objects with their own data, add behaviour with methods, and reuse code with inheritance.

By the end of today you can

  • Explain the difference between a class and an object
  • Write a class with __init__, attributes and methods
  • Understand what self refers to
  • Make objects print nicely with __str__
  • Extend a class with inheritance

So far you've stored data in variables, lists and dictionaries, and written functions to work on it. Classes bundle the two together: the data about a thing and the behaviour that goes with it.

Sketch
A class Dog is drawn as a blueprint with attributes name and age and methods bark() and birthday(). Two arrows labelled Dog(...) lead to two objects: rex with name Rex, age 3, and luna with name Luna, age 5.
Mind map · click a dot to fold, drag to pan

Your first class

main.py · editable
Output
Press Run to execute this code.
TermMeaningIn the example
ClassThe blueprintDog
Object / instanceOne thing built from the classrex, luna
AttributeData stored on an objectrex.name, rex.age
MethodA function defined in the classrex.bark()
__init__Runs when an object is createdsets name and age

What is self?

self is the object a method is working on. rex.bark() is shorthand for Dog.bark(rex), so inside bark, self is rex:

main.py · editable
Output
Press Run to execute this code.

Methods that change state

Methods can update the object's own attributes:

main.py · editable
Output
Press Run to execute this code.

Printing objects nicely: str

main.py · editable
Output
Press Run to execute this code.

Inheritance: build on an existing class

A subclass gets everything from its parent class and can add to it or change it:

Sketch
Animal has name, speak() and introduce(). Dog(Animal) and Cat(Animal) inherit from it and override speak() to return Woof and Meow. Puppy(Dog) inherits from Dog and adds play().
main.py · editable
Output
Press Run to execute this code.

Use super() to extend the parent's __init__ instead of replacing it:

main.py · editable
Output
Press Run to execute this code.

Recap

  • A class is a blueprint; each object is one instance with its own attributes.
  • __init__ runs when an object is created; self is the object itself.
  • Methods are functions that read and update the object's data.
  • __str__ controls how an object prints.
  • class Child(Parent) inherits; override methods to change behaviour and use super() to extend.

Knowledge check

Test what you learned

5 questions · pick an answer to see if you're right

0/5
  1. 1

    What is the relationship between a class and an object?

  2. 2

    When does __init__ run?

  3. 3

    Inside a method, what is self?

  4. 4

    class Puppy(Dog) means...

  5. 5

    What is __str__ used for?

Finished today's lesson?