What is the scope of class variables?
Understanding the scope of class variables in Python
The scope of class variables in Python is the class itself and all its instances (objects). Class variables are accessible from both class methods and instance methods. A change to a class variable is reflected across all instances.
Class variables are defined at the class level and shared among all instances of that class. When you use the self keyword to access a class variable from an instance method, Python first searches for the variable in the instance namespace. If it doesn't find the variable there, it searches for it in the class namespace.
Explanation of the scope of class variables:
- Class Level: Class variables are defined within the class but outside instance methods. They are accessible throughout the class definition and can be used in class methods, instance methods, and other class-level operations.
- Instance Level: When accessing a class variable from an instance method with the self keyword, Python first looks for the variable in the instance's namespace. If it finds the variable there, it uses the instance-level value. Python looks for the variable in the class namespace if it is not found in the instance namespace.
- All Instances: Class variables are shared among all class instances. Changing a class variable from one instance will be reflected in all other instances.
Example: Scope of Python class variables
Code:
class Person:
class_var = '' # This is a class variable
def __init__(self, value):
self.instance_var = value # This is an instance variable
def display(self):
print("Class variable value:", Person.class_var)
print("Instance variable value:", self.instance_var)
# Create two objects of MyClass
obj1 = Person('Voirrey Mitch')
obj2 = Person('Lynsay Izydor')
# Modify class variable using the class name
Person.class_var = 'Ivo Danny'
# Display instance variables of both objects
obj1.display() # Output: Class variable value: Ivo Danny, Instance variable value: Voirrey Mitch
obj2.display() # Output: Class variable value: Ivo Danny, Instance variable value: Lynsay Izydor
In this example, we have a class "Person" with a class variable 'class_var' and an instance variable 'instance_var'. Both objects 'obj1' and 'obj2' share the same 'class_var', and any changes made to class_var affect all instances of the class. However, each object maintains its own separate copy of 'instance_var', and changes made to one object's 'instance_var' do not affect other objects' 'instance_var'. This shows the scope and sharing behavior of class variables in Python.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-interview/what-is-the-scope-of-class-variables.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics