Class and Instance Variables
Explore the concepts of class and instance variables in Python's object-oriented programming. Understand how class variables are shared among all instances while instance variables are unique to each object. This lesson helps you learn proper usage to avoid common mistakes and leverage these variables effectively.
In Python, properties can be defined into two parts:
- Class variables
- Instance variables
Definitions
Class variables
The class variables are shared by all instances or objects of the classes. A change in the class variable will change the value of that property in all the objects of the class.
Instance variables
The instance variables are unique to each instance or object of the class. A change in the instance variable will change the value of the property in that specific object only.
Defining class variables and instance variables
Class variables are defined outside the initializer and instance variables are defined inside the initializer.
In line 2, we have created a class variable and in line 5, we have created an instance variable.
Wrong use of class variables
It is imperative to use class variables properly since they are shared by all the class objects and can be modified using any one of them. Below is an example of wrongful use of class variables:
In the example above, while the instance variable name is unique for each and every object of the Player class, the class variable, formerTeams, can be accessed by any object of the class and is updated throughout. We are storing all players currently playing for the same team, but each player in the team may have played for different former teams.
To avoid this issue, the correct implementation of the example above will be the following:
Now the property formerTeams is unique for each Player class object and can only be accessed by that unique object.
Using class variables smartly
Class variables are useful when implementing properties that should be common and accessible to all class objects. Let’s see an example of this:
Explanation
-
In the example above, we have defined a class variable
teamMembers, which is a list that will be shared by all the objects of the classPlayer. -
This list,
teamMembers, will contain names of all the instances created of thePlayerclass. -
As you can see in line 8, whenever a new object is created, its name is appended in
teamMembers. -
In lines 16 and 20, we can see that
teamMembersis accessed byp1andp2respectively, and both produce the same output.