Python Intermediate: Objects, Errors and Files
Classes and Objects
In this lesson you will
- Define a class with attributes and methods
- Use special methods such as __str__ and __eq__
- Extend a class with inheritance and super()
Introduction
A dictionary can hold the data for a dog: name, age. But what the dog can do (bark, have a birthday) lives somewhere else, in separate functions. A class keeps the data and the behaviour together in one package, called an object. This style is named object-oriented programming.
The simple explanation
A class is a blueprint. An object is a thing built from that blueprint.
class Dog:defines the blueprint. Class names use CapitalWords.__init__is the constructor. It runs when you create an object withDog("Rex", 3)and sets up its data.selfis the object itself. Every method gets it as its first parameter, andself.nameis a value stored on that object.- Each object has its own data.
rexandbellaare independent.
Quick quiz
What is self inside a method?
Printing objects nicely
By default, printing an object shows an unhelpful label. Special methods (with double underscores, called dunder methods) let you customise behaviour.
__str__ is for people reading output, and __repr__ is for developers and debugging.
Class attributes
A variable defined on the class itself is shared by all objects.
Inheritance
A class can inherit from another to reuse and specialise it. The child gets everything from the parent, and can add or replace methods.
super() calls the parent's version. Treating different classes through the same method name, as in the loop, is called polymorphism.
Quick quiz
What does super().__init__(name) do inside a subclass?
Properties: controlled attributes
Use @property to make a method look like an attribute, perhaps with checks.
By convention, a name starting with an underscore (_celsius) means "internal, please do not touch". Python does not enforce it. The last line raises the error from the setter.
Composition: has-a instead of is-a
Inheritance means "is a" (a Dog is an Animal). Often "has a" is clearer: a Library has books.
Try it yourself
Create a class BankAccount with an owner and a balance (starting at 0), a deposit(amount) method and a withdraw(amount) method that raises ValueError when there is not enough money. Add a __str__ that shows the owner and balance.
Summary
- A class is a blueprint, and
__init__sets up each new object.selfis the object. - Special methods like
__str__,__eq__and__add__customise how objects behave. - A child class inherits from its parent.
super()reaches the parent, and each class can override methods. @propertygives controlled, attribute-style access. Prefer composition when the relationship is "has a".
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading