What are Static Variables and Static Methods in Python?

Posted by

Static Variables and Static Methods in Python are really useful and commonly asked about during interviews. It is helpful in optimizing your Python Classes and keeping them organized. In this article, I’ll talk about what they are and show some example code snippets to help you better understand them.

In Python, a static variable is a variable that belongs to a class rather than an instance of a class. This means that the value of a static variable is shared among all instances of a class. In contrast, a non-static variable, or instance variable, belongs to a specific instance of a class, and its value is not shared among other instances of the same class.

A static method is a method that belongs to a class rather than an instance of a class. This means that a static method can be called on a class itself, rather than on an instance of the class.

To create a static variable, simply define it outside any of the class methods. To define a static method, add the following decorator

@staticmethod

Here is an example of a class with a static variable and a static method in Python:

class MyClass:
    # static variable
    my_static_variable = "Hello, World!"

    @staticmethod
    def my_static_method():
        print(MyClass.my_static_variable)

To access the static variable my_static_variable, we can use the class name followed by the variable name, like this:

MyClass.my_static_variable

To call the static method my_static_method, we can use the class name followed by the method name, like this:

MyClass.my_static_method()

Not something like below will return an error

classInstance = MyClass()
print ( classInstance.my_static_variable) # Error
classInstance.my_static_method() # Error

One advantage of using static variables in Python is that they can be accessed directly through the class, without the need to create an instance of the class. This can be useful when you want to define values that are shared among all instances of a class.

Examples of Static Variables and Static Methods in Python

For example, suppose you have a class that represents a bank account. You could use a static variable to store the interest rate that is applied to all accounts, like this:

class BankAccount:
    # static variable
    interest_rate = 0.01

    # instance variables
    def __init__(self, balance):
        self.balance = balance

    # instance method
    def calculate_interest(self):
        return self.balance * BankAccount.interest_rate

In this case, the static variable interest_rate can be accessed directly through the BankAccount class, without the need to create an instance of the class. This allows us to easily change the value of the interest rate for all accounts, without having to update each individual account.

Another advantage of using static methods in Python is that they can be called on a class itself, rather than on an instance of the class. This can be useful when you want to define methods that do not depend on the state of an instance of a class.

For example, suppose you have a class that represents a circle. You could use a static method to calculate the circumference of a circle, given its radius, like this:

class Circle:
    @staticmethod
    def circumference(radius):
        return 2 * 3.14 * radius

In this case, the static method circumference can be called directly on the Circle class, without the need to create an instance of the class. This allows us to easily calculate the circumference of a circle, without having to create a circle object first.

Conclusion

Below is an extended version of the Circle class we had earlier. Along with a static variable and a static method, it also has non-static variables and methods.

We create a two instances of the Circle class and use a couple of f-strings to show how to access the various variables and methods.

import math

class Circle:
  # Static Variable
  shapeName = 'Circle'

  # This is a static method
  @staticmethod
  def get_area(radius):
    return math.floor(math.pi * radius * radius)
  
  def __init__(self,color,radius):
    self.color = color
    self.radius = radius

  # Non-staticmethods, i.e can be invoked by instances
  def get_color(self):
    return self.color

  def get_radius(self):
    return self.radius


redCircle = Circle('red',10.0)
blueCircle = Circle('blue',20.0)

print(f'''This is a {Circle.shapeName}. It is {redCircle.get_color()} in color and has a 
radius of {redCircle.get_radius()}. It has an area of 
{Circle.get_area(redCircle.get_radius())} ''')
print('--------------------')
print(f'''This is a {Circle.shapeName}. It is {blueCircle.get_color()} in color and has a 
radius of {blueCircle.get_radius()}. It has an area of 
{Circle.get_area(blueCircle.get_radius())} ''')

'''
OUTPUT

This is a Circle. It is red in color and has a radius of 10.0. It has an area of 314 
--------------------
This is a Circle. It is blue in color and has a radius of 20.0. It has an area of 1256 
'''

In conclusion, static variables and static methods are important concept in Python that allows for the creation of variables and methods that belong to a class rather than an instance of a class. These can be accessed and called directly through the class, without the need to create an instance of the class. This allows for the creation of values and methods that are shared among all instances of a class, and for the creation of methods that do not depend on the state of an instance of a class. Overall, static variables and methods can be useful for organizing and structuring code in Python

Leave a Reply

Your email address will not be published. Required fields are marked *