Tutorial

Python static method

Published on August 3, 2022
author

Shubham

Python static method

Python static method

In this quick post, we will learn how to create and use a Python static method. We will also have a look at what advantages and disadvantages static methods offer as compared to the instance methods. Let’s get started. python static method

What is a static method?

Static methods in Python are extremely similar to python class level methods, the difference being that a static method is bound to a class rather than the objects for that class. This means that a static method can be called without an object for that class. This also means that static methods cannot modify the state of an object as they are not bound to it. Let’s see how we can create static methods in Python.

Creating python static methods

Python Static methods can be created in two ways. Let’s see each of the ways here:

Using staticmethod()

Let’s directly jump to sample code snippet on how to use the staticmethod() approach:

class Calculator:

    def addNumbers(x, y):
        return x + y

# create addNumbers static method
Calculator.addNumbers = staticmethod(Calculator.addNumbers)

print('Product:', Calculator.addNumbers(15, 110))

Note that we called the addNumbers we created without an object. When we run this program, here is the output we will get: python staticmethod function There were no surprises there. This approach is controlled as at each place, it is possible to create a static method out of a class method as well. Let’s see another approach with the same example here.

Using @staticmethod

This is a more subtle way of creating a Static method as we do not have to rely on a statement definition of a method being a class method and making it static at each place you make it static. Let’s use this annotation in a code snippet:

class Calculator:

    # create addNumbers static method
    @staticmethod
    def addNumbers(x, y):
        return x + y

print('Product:', Calculator.addNumbers(15, 110))

When we run this program, here is the output we will get: python static method annotation This was actually a much better way to create a static method as the intention of keeping the method static is clear as soon as we create it and mark it with the @staticmethod annotation.

Advantages of Python static method

Static methods have a very clear use-case. When we need some functionality not w.r.t an Object but w.r.t the complete class, we make a method static. This is pretty much advantageous when we need to create Utility methods as they aren’t tied to an object lifecycle usually. Finally, note that in a static method, we don’t need the self to be passed as the first argument. API Reference: Python Documentation

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Shubham

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
January 31, 2022

Amazing explanation

- BitchBark

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    August 22, 2021

    Actually, this example works even if the @staticmethod decorator is removed. However, if the class had a mixture of static and non-static methods then the decorator would be necessary.

    - Ken

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      June 17, 2020

      @staticmethod line also the program is same output

      - nag

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        May 10, 2020

        good explanation

        - himanshu

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          April 23, 2020

          Good explanation! But the method is called multiplyNums, but, actually, it is summing the numbers?!

          - WA

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            December 11, 2019

            Thanks …! Wonderful explanation.

            - Shweta

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              November 28, 2019

              What does w.r.t mean?

              - Mike

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                May 12, 2019

                Why are you adding the numbers in the first example?

                - A Discord User#4063

                  Try DigitalOcean for free

                  Click below to sign up and get $200 of credit to try our products over 60 days!

                  Sign up

                  Join the Tech Talk
                  Success! Thank you! Please check your email for further details.

                  Please complete your information!

                  Become a contributor for community

                  Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                  DigitalOcean Documentation

                  Full documentation for every DigitalOcean product.

                  Resources for startups and SMBs

                  The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                  Get our newsletter

                  Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                  New accounts only. By submitting your email you agree to our Privacy Policy

                  The developer cloud

                  Scale up as you grow — whether you're running one virtual machine or ten thousand.

                  Get started for free

                  Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                  *This promotional offer applies to new accounts only.