Static class variables in Python

In Python, static class variables are attributes that are shared among all instances of a class, and they are accessed using the class name itself rather than through instances. They are defined within the class body but outside any methods using the class keyword followed by the variable name.

How static class variables work | Example

class Circle: # Static class variable pi = 3.14159 def __init__(self, radius): self.radius = radius def calculate_area(self): return self.pi * self.radius * self.radius circle1 = Circle(5) circle2 = Circle(8) # Accessing static class variable using class name print("Value of pi:", Circle.pi) # Output: Value of pi: 3.14159 # Accessing static class variable using instance (although it's not recommended) print("Value of pi (via instance):", circle1.pi) # Output: Value of pi (via instance): 3.14159 # Accessing static class variable within instance method print("Area of circle 1:", circle1.calculate_area()) # Output: Area of circle 1: 78.53975 print("Area of circle 2:", circle2.calculate_area()) # Output: Area of circle 2: 201.06176

In the example above, the pi attribute is a static class variable. It is shared among all instances of the Circle class. You can access it using either the class name (Circle.pi) or an instance (circle1.pi), although it's more appropriate to access static variables using the class name.

Conclusion

Static class variables can be useful for defining constants, default values, or data shared across instances of the same class. However, be cautious when modifying them, as changes will affect all instances. If you need instance-specific attributes, you should use instance variables defined within the __init__ method.