Junior — Middle
Can you explain the essence of using static variables inside a class?
sobes.tech AI
Answer from AI
Static variables inside a class in Python are variables shared among all instances of the class. They belong to the class itself, not to any specific object. This is useful when you need to store data that should be the same for all objects, such as a counter for created instances.
Example:
class User:
count = 0 # static variable
def __init__(self, name):
self.name = name
User.count += 1
u1 = User('Alice')
u2 = User('Bob')
print(User.count) # Will output 2
Here, count tracks the number of users created and is accessible through the class and all its objects.