. Advertisement .
. Advertisement .
Whether you are new to programming or coming from another language, static class variables in Python can be a confusing concept. In this tutorial, you will learn how Python defines them and what you can do with those variables.
Static Or Class Variables In Python
An static variable in Python is a type of variable that is declared within a specified class but not within an method. Static or class variables can be referred to via a class within the class in which it is defined, but not directly. A static variable can also be known as a class variables. These variables are limited to a class, therefore they can’t alter the condition of the object.
This is a program that uses class or static variable in python
class fruits(object): count = 0 def __init__(self, name, count): self.name = name self.count = count fruits.count = fruits.count + count def main(): cherry = fruits("cherry", 28); pineapple = fruits("pineapple", 22); print (cherry.count) print (pineapple.count) print (fruits.count) print (cherry.__class__.count) print (type(pineapple).count) if __name__ == "__main__": main()
28 22 50 50 50
This is a program that uses variables defined at the class level
class vehicles: # Python static variable static_Variable = 8 # Access through class print (vehicles.static_Variable) # Access through an instance instance = vehicles() print(instance.static_Variable) # Change within an instance instance.static_Variable = 17 print(instance.static_Variable) print(vehicles.static_Variable)
8 8 17 8
To Define Static Variables in Python
To return a static variable in python we use the staticmethod() method. Here is sample
class Example_Static_Varicable: def random(text_sample): print(text_sample) print("Define Static Variables in Python") Example_Static_Varicable.random = staticmethod(Example_Static_Varicable.random) Example_Static_Varicable.random("Use staticmethod to define")
Use staticmethod to define Define Static Variables in Python
A decorator is a way to add new functionality to an object without modifying its initial structure. Python has a built in decorator called @staticmethod which facilitates the process of defining one or more static variables in a class.
To define a static variable in python we use @staticmethod. Here is sample
class ExStaticVar1: # @staticmethod def random(text_sample1): print(text_sample1) print("Define Static Variables in Python") ExStaticVar1.random("Use @staticmethod to define")
Use @staticmethod to define Define Static Variables in Python
What is class variables in Python?
Python enables object-oriented programming (OOP) with both variables used at both instance and class levels. Class variables are defined directly within a class but outside of any constructor.
They are owned and become attributes of that class, not any specific instance. Instead, those variables are shared with all instances belonging to the class. When you modify a class variable, it affects every instance immediately.
C and C++ programmers typically use the static variable terms to indicate those associated with a class but not any instance of that class.
Python officially doesn’t have this keyword. But if your code is in need of variables that are static within a class and outside the scope of its instances, class variables are what you are looking for. They stand in stark contrast to instance variables, which are attributes of each instance itself.
Check out this example:
# Define a class, with a class and example variable class vehicle: type = "car" def __init__(self, brand): self.brand = brand # Generate two examples of the class X7 = vehicle("BMW") GLS450 = vehicle("Mercedes") print("Class variable:") print(vehicle.type) print("\nFirst example:") print(X7.type) print(X7.brand) print("\nSecond example:") print(GLS450.type) print(GLS450.brand) # Change the class variable print("\nAfter changing the class variable:") vehicle.type = "means of transports" print("\nFirst example:") print(X7.type) print(X7.brand) print("\nSecond example:") print(GLS450.type) print(GLS450.brand)
Class variable: car First example: car BMW Second example: car Mercedes After changing the class variable: First example: means of transports BMW Second example: means of transports Mercedes
We create a class named “vehicle” and assign a value to the type variable. As you can see, the “X7” and “GLS450” instances also inherit this variable. This is true even after we change its value.
Meanwhile, the brand instance variables can have different values for each instance.
When to use class variables in python
Class variables have a lot of use in Python, especially when you need to adhere to the DRY rule:
Store class-wide constants
When you need to define some specific constants that every instance should have access to, class or static variables in Python would come in handy.
Here is an example of using class variables to calculate the circumference of circles:
class Circle(): Pi = 3.1416 def __init__(self, diameter): self.diameter = diameter def circumference(self): return self.Pi * self.diameter perimeter = Circle(7) print('The circumference of the circle is',perimeter.circumference())
The circumference of the circle is 21.9912
Define default values
Another common application of class variables is to create default values for all class instances.
This snippet verifies that each iPhone has the latest IOS version installed.
class IOS: new_version = 16 def __init__(self, current_version): self.current_version = current_version def upgrade_check(self): if self.current_version < self.new_version: print("You are using the old iOS version. You need to upgrade to the latest version.") else: print("You are using the latest iOS version.") iphone11 = IOS(14) iphone12Pro = IOS(16) iphone13 = IOS(16) iphone11.upgrade_check() iphone12Pro.upgrade_check() iphone13.upgrade_check()
You are using the old iOS version. You need to upgrade to the latest version. You are using the latest iOS version. You are using the latest iOS version.
You can define and access class or static variables in Python for different purposes. They are available to every instance of that class. Using these class-specific variables allows you to adopt the best OPP practices and reduce repetition.