Instance vs Class Variables
Part of the Object Oriented Programming section of Coddy's Python journey — lesson 13 of 64.
Instance variables are unique to each object, while class variables are shared by all objects of the same class.
Here is an example of a class with both types of variables
class Student:
# Class variable - shared by all instances
school = "Python High School"
def __init__(self, name, grade):
# Instance variables - unique to each student
self.name = name
self.grade = gradeCreate student objects:
alice = Student("Alice", "A")
bob = Student("Bob", "B")Access instance variables (unique to each object):
print(alice.name) # Alice
print(bob.name) # Bob
print(alice.grade) # A
print(bob.grade) # BAccess class variables (shared by all objects):
print(alice.school) # Python High School
print(bob.school) # Python High School
print(Student.school) # Python High SchoolNow change the class variable:
Student.school = "Python Academy"Check how the change affects all instances:
print(alice.school) # Python Academy
print(bob.school) # Python AcademyOutput:
Alice
Bob
A
B
Python High School
Python High School
Python High School
Python Academy
Python AcademyYou can also create instance variables after object creation:
alice.age = 16 # This creates an instance variable
print(alice.age) # 16
# print(bob.age) # This would cause an error - bob doesn't have ageKey Difference: Instance variables (created with self.variable_name) are unique to each object, while class variables (defined directly in the class) are shared by all objects. Changing a class variable affects all instances.
Challenge
EasyComplete a banking system.. You'll define a BankAccount class in one file and use it in another.
You'll work with:
bank_account.py: Define theBankAccountclass with attributes and methodsdriver.py: Import the class, create accounts, and demonstrate class variables
Follow the TODO comments in both files for step-by-step instructions. The comments will guide you through creating the class with proper variables, methods, and showing how class variables affect all instances.
Cheat sheet
Instance variables are unique to each object, while class variables are shared by all objects of the same class.
Class with both variable types:
class Student:
# Class variable - shared by all instances
school = "Python High School"
def __init__(self, name, grade):
# Instance variables - unique to each student
self.name = name
self.grade = gradeAccess instance variables (unique to each object):
alice = Student("Alice", "A")
bob = Student("Bob", "B")
print(alice.name) # Alice
print(bob.name) # BobAccess class variables (shared by all objects):
print(alice.school) # Python High School
print(bob.school) # Python High School
print(Student.school) # Python High SchoolChanging class variables affects all instances:
Student.school = "Python Academy"
print(alice.school) # Python Academy
print(bob.school) # Python AcademyCreate instance variables after object creation:
alice.age = 16 # This creates an instance variable
print(alice.age) # 16Try it yourself
# TODO: Import the BankAccount class from bank_account.py
from bank_account import BankAccount
# TODO: Create two accounts with these exact details:
# - account1: holder "Alice Smith" with $1000 balance
# - account2: holder "Bob Jones" with $2000 balance
# TODO: Call display_info() for both accounts
# TODO: Change the class variable interest_rate to 0.03 (3%)
# Use this format: BankAccount.interest_rate = 0.03
# TODO: Print the text "After interest rate change:"
# TODO: Call display_info() for both accounts again to show they both have the new interest rateThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe self ParameterMethodsAttributesConstructor Method (__init__)Recap - Simple Calculator4Inheritance
Basic InheritanceThe super() FunctionMethod OverridingMultiple InheritanceMethod Resolution OrderRecap - Employee Hierarchy7Special Methods
Magic Methods IntroductionOperator OverloadingContainer Magic MethodsRecap - Custom List10Design Patterns Part 1
Intro to design patternSingleton PatternFactory PatternObserver PatternStrategy Pattern2Decorators
Introduction to DecoratorsProperty DecoratorStatic Method DecoratorClass Method Decorator5Polymorphism
Method Overriding RevisitedDuck TypingAbstract Classes and MethodsInterface DesignRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceMixinsStatic and Class MethodsClass DecoratorsContext Managers3Class Properties
Instance vs Class VariablesProperty DecoratorsPrivate AttributesRecap - Bank Account Manager6Encapsulation
Public, Protected, Private MemAccess ModifiersInformation HidingProperty Decorators AdvancedRecap - Student Records System12Project: Library Management
Project OverviewBook and User Classes