Class variable vs. Instance variable

OOP allows for variables to be used at the class level or the instance level.

  • When we expect variables are going to be consistent across instances, or when we would like to initialize a variable, we can define that variable at the class level.
  • When we anticipate the variables will change significantly across instances, we can define them at the instance level.

Class variable

Because they are owned by the class itself, class variables are shared by all instances of the class. They will generally have the same value for every instance.

We can access a class variable via an instance or via the class name. But be careful, if you want to change a class variable, you have to do it with the notation “classname.classvariable”. Otherwise, you’ll create a new instance variable.

Defined outside of all the methods, class variables are typically placed right below the class header and before the constructor method.

Instance variable

Instance variables are owned by instances of the class. This mean that for each object or instance of a class, the instance variables are different.

We will have to define instance variables with self. Instance variables are defined within methods.

Example: Class variable vs. Instance variable

class Dog:
    species= "Coggy"  # class variable
    def __init__(self, name, age): = name # instance variables
        self.age = age

    def __str__(self):
        return "Name:{} Age:{} Species:{}".format(, self.age, Dog.species)

Mic = Dog("Mic", 3)
Ben = Dog("Ben", 2)

Name:Mic Age:3 Species:Coggy
Name:Ben Age:2 Species:Coggy

Making use of class- and instance variables can ensure that out code adheres to DRY (Don’t Repeat Yourself) principle to reduce repetition within code.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s