Junior
What is a static variable in Python?
sobes.tech AI
Answer from AI
In Python, a static variable is a variable belonging to the class rather than a specific instance of the class. Its value is shared among all instances of the class.
Main characteristics:
- Scope: Within the class.
- Lifetime: Exists throughout the runtime of the program.
- Access: Can be accessed via the class name or through an instance of the class (though accessing via the class name is preferred to indicate its static nature).
Example of usage:
class MyClass:
# Static variable
static_variable = 10
def __init__(self, instance_variable):
# Instance variable
self.instance_variable = instance_variable
# Accessing static variable via class name
print(MyClass.static_variable)
# Creating instances
obj1 = MyClass(20)
obj2 = MyClass(30)
# Accessing static variable via instances
print(obj1.static_variable)
print(obj2.static_variable)
# Changing static variable via class name
MyClass.static_variable = 15
# The value has changed for all instances
print(obj1.static_variable)
print(obj2.static_variable)
In this example, static_variable is a static variable. It exists as a single instance for the entire MyClass class, and its value is shared among objects obj1 and obj2. Changing the value via the class name MyClass.static_variable = 15 affects all instances.
It is important to distinguish static class variables from instance variables (self.instance_variable), which are unique to each object (instance) of the class.