OOP – Class Variables vs Instance Variables, online
Six activities your students do on their own devices. See who's finished, and their scores.
Learning
Understanding
Testing
OOP – Class Variables vs Instance Variables in one minute
What students need to know
Class variables are defined directly in the class body, outside any method. self.name stores data that belongs to one specific object.
Instance variables use self — they're created in __init__ and belong to each object. count is defined on the class itself, so all Dog instances share the same count.
Mistakes students make
- count should be a class variable, not instance. Define at class level.
- Redundant species is already a class variable. No need to set in __init__.
- Use Dog.count to modify the class variable count alone is undefined.
- self.count creates an instance variable that shadows the class variable.
PREVIOUS · MODULE 53OOP – Practical Application
YOU ARE HERE · MODULE 54OOP – Class Variables vs Instance Variables
NEXT · MODULE 55OOP – Private Attributes (underscore convention)
What students will learn in this module
Every question in Module 54
Quick questions
- Where is a class variable defined?AInside the class but outside methodsBInside __init__
- Where is an instance variable defined?AOutside the classBInside __init__ using self.var
- class Dog:\n count = 0\nIs count shared between objects?AYes it's a class variableBNo each object has its own
- self.name vs Dog.species what's the difference?Aself.name is per-object, Dog.species is sharedBThey are the same
- Dog.count += 1 what happens?ACreates a new objectBIncrements the shared counter
Key terms
Students type the meaning of:
Class variableInstance variableShared stateUnique state
Match the pairs
species = 'Canine' # in __init__Match it to what it doesspecies = CanineMatch it to what it doesspecies = 'Canine' # in class bodyMatch it to what it doesself.name = nameMatch it to what it doesbool(0)Match it to what it doesbool([])Match it to what it doesFill in the blanks
class Dog: _______ = 'Canine'class Dog: count = 0 def ________(self, name): Dog.count += 1class Dog: count = 0 def __init__(self, name): ____.count += 1d = Dog('Rex') print(d.____)print(___.species)
Spot the error
Question 1
Aclass Dog:B def __init__(self, name):C self.name = nameD self.count += 1 # track total dogs
Question 2
Aclass Dog:B species = 'Canine'C def __init__(self, name):D species = 'Canine'E self.name = name
Question 3
Aclass Dog:B count = 0C def __init__(self, name):D self.name = nameE count += 1
Question 4
Aclass Dog:B count = 0C def __init__(self, name):D self.name = nameE self.count += 1
Question 5
Aclass Dog:B species = 'Canine'CDd = Dog()Ed.species = 'Feline'Fprint(Dog.species) # expects Feline
