Python @staticmethod

There can be some functionality that relates to the class, but does not require any instance(s) to do some work, static methods can be used in such cases. A static method is a method which is bound to the class and not the object of the class. It can’t access or modify class state. It is present in a class because it makes sense for the method to be present in class. A static method does not receive an implicit first argument.

Syntax:

class C(object):
    @staticmethod
    def fun(arg1, arg2, ...):
        ...

Returns: a static method for function fun.

When function decorated with @staticmethod is called, we don’t pass an instance of the class to it as it is normally done with methods. It means that the function is put inside the class but it cannot access the instance of that class.

Example #1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to 
# demonstrate static methods
  
class Maths():
      
    @staticmethod
    def addNum(num1, num2):
        return num1 + num2
          
# Driver's code
if __name__ == "__main__":
      
    # Calling method of class
    # without creating instance
    res = Maths.addNum(1, 2)
    print("The result is", res)

chevron_right


Output:

The result is 3

Example #2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to
# demonstrate static methods
  
class Person: 
    def __init__(self, name, age): 
        self.name = name 
        self.age = age 
        
    # a static method to check if a Person is adult or not. 
    @staticmethod
    def isAdult(age): 
        return age > 18
          
# Driver's code
if __name__ == "__main__":
    res = Person.isAdult(12)
    print('Is person adult:', res)
      
    res = Person.isAdult(22)
    print('\nIs person adult:', res)

chevron_right


Output:

Is person adult: False

Is person adult: True



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.