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.
Your first class
| Term | Meaning | In the example |
|---|---|---|
| Class | The blueprint | Dog |
| Object / instance | One thing built from the class | rex, luna |
| Attribute | Data stored on an object | rex.name, rex.age |
| Method | A function defined in the class | rex.bark() |
__init__ | Runs when an object is created | sets 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:
Methods that change state
Methods can update the object's own attributes:
Printing objects nicely: str
Inheritance: build on an existing class
A subclass gets everything from its parent class and can add to it or change it:
Use super() to extend the parent's __init__ instead of replacing it:
Recap
- A class is a blueprint; each object is one instance with its own attributes.
__init__runs when an object is created;selfis 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 usesuper()to extend.
Knowledge check
Test what you learned
5 questions · pick an answer to see if you're right
- 1
What is the relationship between a class and an object?
- 2
When does __init__ run?
- 3
Inside a method, what is self?
- 4
class Puppy(Dog) means...
- 5
What is __str__ used for?
Finished today's lesson?