Staticmethod Decorator
Define Static Method using @staticmethod Decorator in Python
Section titled “Define Static Method using @staticmethod Decorator in Python”The @staticmethod is a built-in decorator that defines a static method in the class in Python. A static method doesn’t receive any reference argument whether it is called by an instance of a class or by the class itself.
@staticmethod
@staticmethod Characteristics
Section titled “@staticmethod Characteristics”- Declares a static method in the class.
- It cannot have cls or self parameter.
cls``self- The static method cannot access the class attributes or the instance attributes. - The static method can be called using ClassName.MethodName() and also using object.MethodName().
ClassName.MethodName()``object.MethodName()- It can return an object of the class.
The following example demonstrates how to define a static method in the class:
class Student: name = 'unknown' # class attribute
def __init__(self): self.age = 20 # instance attribute
@staticmethod def tostring(): print('Student Class')`class Student: name = ‘unknown’ # class attribute
def __init__(self): self.age = 20 # instance attribute
@staticmethoddef tostring(): print('Student Class')`Above, the Student class declares the tostring() method as a static method using the @staticmethod decorator. Note that it cannot have self or cls parameter.
Student``tostring()``@staticmethod``self``cls
The static method can be called using the ClassName.MethodName() or object.MethodName(), as shown below.
ClassName.MethodName()``object.MethodName()
#calling static methodStudent.tostring() #'Student Class'Student().tostring() #'Student Class'
std = Student()std.tostring() #'Student Class'`#calling static method
Student.tostring() #‘Student Class’
Student().tostring() #‘Student Class’
std = Student() std.tostring() #‘Student Class’`Try it The static method cannot access the class attributes or instance attributes. It will raise an error if try to do so.
class Student: name = 'unknown' # class attribute
def __init__(self): self.age = 20 # instance attribute
@staticmethod def tostring(): print('name=',name,'age=',self.age)
Student.tostring() #error`class Student: name = ‘unknown’ # class attribute
def __init__(self): self.age = 20 # instance attribute
@staticmethoddef tostring(): print('name=',name,'age=',self.age)Student.tostring() #error`Try it
@classmethod vs @staticmethod
Section titled “@classmethod vs @staticmethod”The following table lists the difference between the class method and the static method:
class methodClassName.MethodName()``object.MethodName()``ClassName.MethodName()``object.MethodName()