w3resource

What are Python class variables?

Python class variables: Shared attributes among Instances

Python class variables are variables that are shared among all instances (objects) of a class. Unlike instance variables, which have a separate copy for each object, class variables are associated with the class itself, and any modification to the class variable affects all instances of the class.

Class variables are defined within the class, outside of any instance methods, and are typically placed at the top level of the class definition. They are prefixed with the class name and can be accessed using either the class name or the instance name.

Example: Python class variables

class Student:
    student_class_var = 0  # Class variable
    def __init__(self, value):
        self.student_instance_var = value  # Instance variable
    def display(self):
        print("Class variable value:", Student.student_class_var)
        print("Instance variable value:", self.student_instance_var)
# Create two objects of Student
obj1 = Student(12)
obj2 = Student(14)
# Access class variable using the class name
print("Class variable value (using class name):", Student.student_class_var)
# Access class variable using an instance
print("Class variable value (using instance):", obj1.student_class_var)
# Modify class variable using the class name
Student.student_class_var = 17
# Display instance variables of both objects
obj1.display()  # Output: Class variable value: 17, Instance variable value: 12
obj2.display()  # Output: Class variable value: 17, Instance variable value: 14

In the example above, we have a class "Student" with a class variable 'student_class_var' and an instance variable 'student_instance_var'. Both objects 'obj1' and 'obj2' share the same 'student_class_var', and any changes made to 'student_class_var' affect all instances of the class. However, each object maintains its own separate copy of 'student_instance_var', and changes made to one object's 'student_instance_var' do not affect other objects' 'student_instance_var'.



Follow us on Facebook and Twitter for latest update.