Classes and OOP
Object-oriented programming (OOP) bundles data and the functions that work on it into objects. A class is the blueprint; an object (or instance) is a thing built from it. You've been using objects all along: every string, list and dict is one.
Your first class
__init__is the initialiser. It sets up each new object.selfis the object the method is working on. Python passes it automatically:rex.add_trick("sit")callsDog.add_trick(rex, "sit").- Each object has its own attributes: Rex's tricks aren't Bella's.
Class attributes and special methods
Methods with double underscores ("dunder" methods) hook your class into Python's syntax: len(), +, ==, for loops, print… That's how your own classes can feel built-in.
Encapsulation and properties
By convention, a leading underscore means "internal, don't touch from outside". A @property looks like an attribute but runs code, which is perfect for validation and computed values:
Inheritance
A class can inherit from another, reusing its code and adding or changing behaviour:
Calling the same method on different types and getting type-specific behaviour is called polymorphism.
💡 Prefer composition ("has a") over deep inheritance ("is a") trees. A
Carhas anEngine; it isn't one. Short, shallow hierarchies are easier to change.
Dataclasses: less boilerplate
For classes that mainly hold data, @dataclass writes __init__, __repr__ and __eq__ for you:
Class methods and static methods
Pattern matching on objects
match works with classes, which makes handling different object types elegant:
Practice
- Create a
Rectangledataclass withwidthandheight, plusareaandperimeterproperties, and anis_square()method. - Write a
ShoppingCartclass withadd(product, qty),remove(product)andtotal(), using theProductdataclass above. - Give
ShoppingCarta__len__method (number of items) and a__str__that lists the contents.
1.What is self in a method?
2.Which method makes print(obj) show something friendly?
3.What does @dataclass generate for you?