python-@staticmethod decorator

Created with Sketch.

@staticmethod decorator

The @staticmethod is a built-in decorator in Python which defines a static method.
A static method doesn’t receive any reference argument whether it is called by an instance of a class or by the class itself.
The following notation is used to declare a static method in a class:

Example: Define Static Method
class person:
    @staticmethod
    def greet():
        print("Hello!")

 

In the above example, @staticmethod is applied to the greet() method. So, the greet() method can be called using the class name person.greet(), as well as using the object.


>>> person.greet()
Hello!
>>> p1=person()
>>> p1.greet()
Hello!

Even though both person.greet() and p.greet() are valid calls, the static method receives reference of neither.
Hence it doesn’t have any arguments – neither self nor cls.

Leave a Reply

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