Python is a popular high-level programming language, known for its simplicity, versatility, and ease of use. One of the useful features of Python is the ability to define static variables. In this article, we will discuss what are static variables in Python and provide some examples.
What are Static Variables?
Static variables are variables that are shared among all instances of a class. They are also known as class variables because they are defined at the class level, rather than at the instance level. Static variables are useful when you want to store data that is common to all instances of a class. For example, you might use a static variable to keep track of the total number of instances of a class that have been created.
Static variables are defined using the following syntax:
1 2 | class ClassName: static_var = value |
Here, `static_var` is the name of the static variable, and value is the initial value of the variable. Static variables can be accessed using the class name, rather than an instance of the class:
1 | ClassName.static_var |
Example
Let’s understand with an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class Car: number_of_cars = 0 def __init__(self, make, model): self.make = make self.model = model Car.number_of_cars += 1 def display(self): print(f"Make: {self.make}, Model: {self.model}") c1 = Car("Toyota", "Corolla") c2 = Car("Honda", "Civic") c3 = Car("Ford", "Mustang") print(Car.number_of_cars) # Output: 3 |
In the above example, we have defined a static variable `number_of_cars` which keeps track of the total number of cars created. Every time we create a new car object, the `__init__()` method increments the value of `number_of_cars` by `1`. Finally, we print the value of `number_of_cars` using the class name, which gives us the total number of cars created.
Benefits of Using Static Variables
- Static variables are shared among all instances of a class, which means that you can store data that is common to all instances of a class.
- Static variables can be accessed using the class name, which makes the code more readable and easier to understand.
- Static variables can be used to maintain state across multiple instances of a class.
- Static variables are initialized only once when the class is defined, which can help improve the performance of your code.
Conclusion
Static variables are a powerful feature of Python that can help you write cleaner, more efficient code. They are particularly useful when you want to store data that is common to all instances of a class. In this article, we discussed what static variables are and provided some examples of how they can be used. Hopefully, this article has given you a better understanding of how static variables work in Python.