Skip to main content
Practice

Class Variables Shared Across Objects

A class variable is a variable that belongs to the class and whose value is shared across all objects created by that class.

Class variables are defined inside a class, typically at the beginning of the class definition.

Unlike instance variables which have independent values for each object created using the __init__ constructor, class variables have a shared value across all objects created by the class.


Example of Using Class Variables

Example of Using Class Variables
class MyClass:
# Class variable
class_variable = "Shared Variable"

def __init__(self, name):
# Instance variable
self.name = name

# Accessing class variable
print(MyClass.class_variable)
# Output: Shared Variable

# Creating instances
obj1 = MyClass("Object1")
obj2 = MyClass("Object2")

# Class variable shared by all instances
print(obj1.class_variable)
# Output: Shared Variable
print(obj2.class_variable)
# Output: Shared Variable

# Modifying the class variable
MyClass.class_variable = "Modified Value"
print(obj1.class_variable)
# Output: Modified Value
print(obj2.class_variable)
# Output: Modified Value

# Instance variables remain individual
print(obj1.name)
# Output: Object1
print(obj2.name)
# Output: Object2

In this code, class_variable is a class variable of the MyClass class, and its value is shared across all objects created by MyClass.

The instances obj1 and obj2 have their own name instance variables, which maintain independent values for each object.

Class variables can be accessed using the class name, and modifying the value of a class variable affects all instances.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.