OOP – Class Variables vs Instance Variables, online

Six activities your students do on their own devices. See who's finished, and their scores.

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.

Discover other journeys with this module

What students will learn in this module

Every question in Module 54

Quick questions

  1. Where is a class variable defined?AInside the class but outside methodsBInside __init__
  2. Where is an instance variable defined?AOutside the classBInside __init__ using self.var
  3. class Dog:\n count = 0\nIs count shared between objects?AYes it's a class variableBNo each object has its own
  4. self.name vs Dog.species what's the difference?Aself.name is per-object, Dog.species is sharedBThey are the same
  5. Dog.count += 1 what happens?ACreates a new objectBIncrements the shared counter

Key terms

Students type the meaning of:

  • Class variable
  • Instance variable
  • Shared state
  • Unique state

Match the pairs

species = 'Canine' # in __init__Match it to what it does
species = CanineMatch it to what it does
species = 'Canine' # in class bodyMatch it to what it does
self.name = nameMatch it to what it does
bool(0)Match it to what it does
bool([])Match it to what it does

Fill in the blanks

  1. class Dog:
        _______ = 'Canine'
  2. class Dog:
        count = 0
        def ________(self, name):
            Dog.count += 1
  3. class Dog:
        count = 0
        def __init__(self, name):
            ____.count += 1
  4. d = Dog('Rex')
    print(d.____)
  5. 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