Home » Python

Static methods in Python

Python static methods: In this tutorial, we are going to learn about the static methods with examples in Python programming language.
Submitted by Sapna Deraje Radhakrishna, on December 11, 2019

Python static methods

Static methods are similar to python class-level methods while the static method is bound to a class rather than the object for the given class.

Creating a python static method

1) Using staticmethod()

Below example demonstrates the implementation of staticmethod(),

class Multiply:
    def perform(x,y):
        return x * y

Multiply.perform = staticmethod(Multiply.perform)
print("Multiplication of {} and {} is {}".format(5,4, Multiply.perform(4, 5)))

Output

Multiplication of 5 and 4 is 20

2) Using @staticmethod

Below example demonstrates the implementation of @staticmethod,

class Multiply:
    @staticmethod
    def perform(x,y):
        return x * y

print("Multiplication of {} and {} is {}".format(5,4,Multiply.perform(4, 5)))

Output

Multiplication of 5 and 4 is 20

Note: The @staticmethod is more pythonic way to declare a method to be a static method.

Advantages of using Static method

  • Very clear use case
  • When there is a use case not wrt object but wrt class, the method is made a static method. This approach is advantageous while implementing utilities method.
  • In a static method, the self is not passed as a first argument.





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.