First, a quick review if you're new to object oriented programming. A class is template for creating objects, and an instance is the object itself. Classes often represent something in the real-world, so imagine if you wanted to represent a classroom full of students. You might create a class called Student, which is a template that defines various attributes of a student. Each student, then, is an instance of the Student class.
When dealing with any sort of data, some attributes are going to be unique and some will be shared. Consider our student example, each student in this classroom has the same room number and the same teacher, but they each have a unique name, age, and favorite subject.
Class variables
Class variables are usually variables that are shared by all instances. And they are defined like this:
class Student:
teacher = 'Mrs. Jones' # class variable
Each instance of the class will have the same value for these variables:
tom = Student()
susan = Student()
print(tom.teacher)
>> "Mrs. Jones"
print(susan.teacher)
>> "Mrs. Jones"
Instance variables
Instance variables (also called data attributes) are unique to each instance of the class, and they are defined within a class method, like this:
class Student:
teacher = 'Mrs. Jones' # class variable
def __init__(self, name):
self.name = name # instance variable
See how each instance now contains a unique value for name:
tom = Student('Tom')
susan = Student('Susan')
print(tom.name)
>> "Tom"
print(susan.name)
>> "Susan"
Summary
This was only a basic overview of class and instance variables. We'll go into more depth in the upcoming steps, but the most important take away is that class variables are typically used for values that are shared among all instances of a class while instance variables are used for values that are unique to each instance.