Explain Python static method

Explain the Python static method

In this article, we’ll explore the creation and use of the Python static method. Additionally, we’ll explain the advantages and disadvantages of static methods compared to instance methods. Let’s start.

Python static methods differ from instances because they aren’t tied to a specific object. This means they can’t access or modify the object’s information. Unlike instance methods, static methods don’t automatically receive “self” or “cls” parameters from Python, so they can’t access or modify the class’s state.

Python Static method

In reality, you use static methods in a class to define utility methods or groups of logically related functions. It’s like creating a regular function, but you put it inside a class to make it a static method.

Syntax


class C(object):
@staticmethod
def funname(arg1, arg2, ...):
...
returns: This static method for function funname.

Example


class abc:
@staticmethod
def demo():
pass
print ('static method define')

Output

static method define

Calling a Static method

If you have a static method in a class in Python, you can call it directly using the class name without creating an instance of the class. However, it’s important to note that a static method can only access static variables, not instance variables.

Syntax


ClassName.methodName(parameters)

Here, ClassName is the name of the class, and methodName is the name of the static method you want to call. You provide any necessary parameters within the parentheses.

Example


class demo:
@staticmethod
def testdemo(a):
print('This is a static method', a)
# calling a static method
demo.testdemo(12)
# calling using object
dm = demo()
dm.testdemo(12)

Output

This is a static method 12

This is a static method 12

Calling Static Method from Another Method

Now, let’s look at how we can invoke a static method from another static method within the same class. In this context, we’ll also clarify the distinctions between static and class methods.

Example


class Animaltest :
@staticmethod
def first_test_static_method():
print('first_static_method')
@staticmethod
def second_test_static_method() :
Animaltest.first_test_static_method()
@classmethod
def class_method(c) :
c.second_test_static_method()
# calling the class method
Animaltest.class_method()

Output

first_static_method

Save $100 in the next
5:00 minutes?

Register Here

Creating a static method using @staticmethod Decorator

To designate a method as static in Python, you can use the @staticmethod decorator. This built-in function decorator, denoted by @staticmethod, declares a method as static. It functions as an expression assessed immediately after defining the respective function.

Static methods represent a distinct category of methods in programming. In certain situations, you may create code within a class that doesn’t require using the actual object itself. These methods, often referred to as utility methods, can operate independently without relying on an object (self-parameter). Given their static nature, we explicitly declare them as such. Furthermore, they can be invoked from other class methods, adding to their versatility within the class structure.

Example

For example, let’s create a static method named information() that, when given a “kingdom,” provides a list of all the necessary requirements that must be met for that specific kingdom −


class WildCreature:
def __init__(self, name, species, habitat):
self.name = name
self.species = species
self.habitat = habitat
@staticmethod
def creature_info(habitat):
if habitat == 'Forest':
info = ['wolf', 'Canidae', 'Forest']
else:
info = ['wolf']
return info
# the instance method
def display_info(self):
# calling the static method from the instance method
info = self.creature_info(self.habitat)
for i in info:
print('Information collected', i)
# Create an instance of the WildCreature class with a different name
wolf_instance = WildCreature('Gray Wolf', 'Canidae', 'Forest')
# Call the instance method
wolf_instance.display_info()

Output

Information collected wolf
Information collected Canidae
Information collected Forest

The staticmethod() function

Specific programs might employ the traditional approach of defining static methods using the staticmethod() function instead of the modern decorator syntax.

If your codebase needs to accommodate earlier Python versions (specifically 2.2 and 2.3), it’s recommended to define static methods exclusively using the staticmethod() function. However, for versions beyond this and a more contemporary and widely accepted practice, the @staticmethod decorator is recommended.

Syntax


staticmethod(function)

The method to be converted into a static method is named “function.” This method, upon transformation, returns the resulting static method.

Example

class demo:
def testdemo(a):
print('This is static method', a)
# converting to the static method
demo.testdemo = staticmethod(demo.testdemo)
# calling the static method
demo.testdemo(2)

Output

This is static method 2

Note:  if you find yourself needing a reference to a function within a class body yet wish to avoid automatic conversion into an instance method, employing the staticmethod() approach can be a valuable solution.

Save $100 in the next
5:00 minutes?

Register Here

Conclusion

In conclusion, this article delved into Python static methods, which operate independently of class instances and lack access to object-specific information. Static methods are helpful for utility functions within a class. They can be defined using the @staticmethod decorator or the staticmethod() function for compatibility with older Python versions. These methods are invoked directly with the class name and are distinct from instance methods. Their concise nature and versatility make them valuable for organizing code within a class. To learn more about Python Strings, refer to this article.