In Python, the @staticmethod decorator is used to define a static method, which is a method that is bound to a class rather than an instance of the class. Static methods are not associated with a specific object, and they do not have access to the instance variables of the class.
To define a static method in Python, you can use the @staticmethod decorator followed by the name of the method and its arguments. For example:
class MyClass:
def __init__(self, x):
self.x = x
@staticmethod
def static_method(y):
print(y)
obj = MyClass(10)
obj.static_method(20) # 20
Static methods are useful when you want to define a function that is related to a class, but that does not need to access any instance-specific data. They are also often used to define utility functions that are used by multiple instances of a class.
So, we can do this:
class MyMath:
@staticmethod
def add(a,b):
return a+b
@staticmethod
def subtract(a,b):
return a-b
@staticmethod
def mult(a,b):
return a*b
@staticmethod
def divide(a,b):
if b == 0: return None
return a/b
print(MyMath.add(5,3))
print(MyMath.subtract(5,3))
print(MyMath.mult(5,3))
print(MyMath.divide(5,3))
This decorator is used to define a class method, which is a method that is bound to a class and has access to the class variables as well as the instance variables.
The difference between a staticmethod and a classmethod is:
Staticmethod knows nothing about the class and just deals with the parameters.
Classmethod works with the class since its parameter is always the class itself.
Here is an example:
class MyClass:
def instance_method(self):
print("This is an instance method")
@classmethod
def class_method(cls):
print("This is a class method")
# Create an instance of the class
my_instance = MyClass()
# Call instance method
my_instance.instance_method()
# Call class method
MyClass.class_method()
I have not yet used a class method in real world code.
This decorator is used to define a method as a "getter" for a class attribute, allowing it to be accessed like a regular attribute.