What is @staticmethod decorator?
In Python, the @staticmethod decorator defines a static method within a class. A static method is a method that belongs to a class rather than an instance of the class.
It does not have access to the instance or its attributes and does not modify the state of the instance.
Here is an example of using @staticmethod:
class StaticMethodClass:
class_variable = "I am a class variable"
def __init__(self, value):
self.value = value
@staticmethod
def static_method():
print("This is a static method")
# Creating an instance of the class
obj = StaticMethodClass(value=189)
# Accessing the static method using the class itself
StaticMethodClass.static_method() # Output: This is a static method
# Accessing the static method using an instance (although not common or recommended)
obj.static_method() # Output: This is a static method
Key points about @staticmethod:
- It is a decorator that defines a method as a static method.
- Static methods are bound to the class and not to the instance of the class.
- They can be called on the class itself or an instance of the class.
- They cannot access or modify the instance state (i.e., instance attributes).
Static methods are helpful when you have a method that does not depend on the instance state and does not need to modify it. They are often used for utility functions related to the class but do not depend on specific instances.
It's worth noting that static methods are not commonly used in Python, and instance methods or class methods are often preferred for better readability and maintainability.