Instance and Class Variables
Introduction
Welcome to Sharing Behavior Between Classes in Python! We are beginning Unit 1 of 3, so we are at the start of our work with shared class behavior. In earlier courses, we defined classes, used self, built constructors with __init__, let objects interact through methods, and assembled objects from smaller parts through composition. Now we will ask a new question: when several objects belong to the same class, which data should they share, and which data should stay separate?
In this lesson, we will learn how to:
- Distinguish instance variables (data that belongs to one object) from class variables (data shared by every object of the class).
- Read a class variable through the class itself and through any instance.
- Use a shared counter on the class to assign the next account number whenever a new object is created.
- See what happens when we assign to a class variable through one instance — a behavior called shadowing.
Instance Variables Belong to One Object
We will work through a BankAccount class step by step. To start, the constructor stores data on each new account through self:
When we assign an attribute through self inside a method, that attribute belongs to the particular object we are working on. We have been doing this since we met __init__: self.owner = owner stores data on one account, not on the class as a whole. Attributes created this way are instance variables — each object gets its own copy.
Let us create two accounts and see what that means:
Alice's owner is "Alice" and her balance is 1000. Bob's owner is "Bob" and his balance is 500. Changing Alice's balance does not change Bob's balance, because those values live on separate objects.
Class Variables Are Shared by All Instances
Sometimes several objects need to agree on a value. A bank might set one interest rate for every account, or use one name across all branches. For data like this, we define a class variable directly in the class body, outside any method:
These names sit at the class level, not inside __init__. Every BankAccount object can read them, and there is only one bank_name, one interest_rate, and one next_account_number for the whole class. Our instance variables (owner, balance) still belong to each account individually; the class variables belong to BankAccount itself.
