Skip to main content
Module 7 · Lesson 1 of 425/36 in the course~18 min
Module lessons (1/4)

Classes and instances

Lesson preview5 hands-on exercises readyPython Course · Module 7 — Classes and modules

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 on self, 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__ before Class.__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

  1. 11. Constructor __init__ and status of the instance
  2. 22. Class vs shadow attributes on the instance
  3. 33. Methods that change the state safely
  4. 44. Expose @classmethod as an alternate constructor
  5. 5Check for understanding
  6. 6Test yourself
Pro Lesson · Module 7 — Classes and modules

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.