Module lessons (1/4)
Classes and instances
class, __init__, instance attributes and methods, self, and class vs instance attributes.
What you'll learn in this lesson
- Define Python classes with
__init__, instance attributes onself, and operation methods. - Clearly distinguish instance attributes (specific to the single object) from class attributes (shared by all instances).
- Understand how Python solves attribute matching (
istance.__dict__beforeClass.__dict__). - Avoid the classic bug of mutable defaults shared at the class level.
Overview
A class is a blueprint that describes the data structure and behaviors of a family of objects. Each instance built from that template has its own dictionary of private attributes (self.__dict__), but shares the method code defined only once on the class.
When you call account.deposit(50), Python does not duplicate the code of deposit inside each object: it looks for deposit on BankAccount and invokes it automatically passing account as the first argument, conventionally called self.
Sections covered in this lesson
- 11. Constructor
__init__and status of the instance - 22. Class vs shadow attributes on the instance
- 33. Methods that change the state safely
- 44. Expose
@classmethodas an alternate constructor - 5Check for understanding
- 6Test yourself
Unlock "Classes and instances" and the full Python Course curriculum
class, __init__, instance attributes and methods, self, and class vs instance attributes.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Python Course plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.