Python staticmethod()

Static methods are special cases of class methods. They’re bound to a class rather than an instance, so they’re independent on any instance’s state. Python’s built-in function staticmethod() prefixes a method definition as an annotation @staticmethod. This annotation transforms a normal instance method into a static method. The difference between static (class) methods and instance methods is that they don’t require an instance to be callable.

In this tutorial, I’ll show you one of Python’s little-known secrets that separate the intermediates from the experts: static methods. A static method is a special case of a class method. You may know the difference between an instance method and a class method conceptually. (If you don’t, this tutorial is for you.) But do you also know how to create a static method in Python?

If not, read on, because this tutorial will show you!

Syntax Class Method

Syntax: 
staticmethod(function)    # <--- This is considered unpythonic
@staticmethod                        # <--- As a prefix before the used method

You can declare a static method is the following decorator syntax—this is the most Pythonic way:

class C:
    @staticmethod
    def f(arg1, arg2, ...):
        None

C.f(arg1, arg2, ...)

How to Call a Static Method?

There are two ways of calling a static method:

  • You can call it on a class such as C.f(arg1, arg2, ...), or
  • You can call it on an instance such as C().f(arg1, arg2, ...).

In contrast to a class method, Python doesn’t implicitly pass a reference to the class itself as a first argument.

Static Method Application — Factory Pattern

You can use the static method to allow people to create different variants of a Coffee class:

class Coffee:

  def __init__(self, milk, beans):
    self.milk = milk # percentage
    self.coffee = 100-milk # percentage
    self.beans = beans


  def __repr__(self):
    return f'Milk={self.milk}% Coffee={self.coffee}% Beans={self.beans}'


  @staticmethod
  def cappuccino():
    return Coffee(80, 'Arrabica')
  

  @staticmethod
  def espresso_macchiato():
    return Coffee(30, 'Robusta')
  

  @staticmethod
  def latte():
    return Coffee(95, 'Arrabica')


print(Coffee.cappuccino())
print(Coffee.espresso_macchiato())
print(Coffee.latte())

This is called the factory pattern: the static methods are instance factories—they produce new instances according to their implementations. For example, the Coffee.cappuccino() method creates a special type of Coffee with an initial selection of 80% milk and Arrabica beans.

The output of this code snippet is:

Milk=80% Coffee=20% Beans=Arrabica
Milk=30% Coffee=70% Beans=Robusta
Milk=95% Coffee=5% Beans=Arrabica

Interactive Example Static Method

The following interactive code shell allows you to play with this example and deepen your skills.

Exercise: Can you create another coffee specialty?

Static Method is a Function Decorator

Decorators help to add functionality to existing code without having to modify the code itself. Decorators are so-called because they decorate code, they do not modify the code, but they make the code do different things using decoration. Now that we have understood closures, we can work our way step by step to understanding and using decorators.

The @staticmethod is a function decorator. It’s short for calling staticmethod(m) for the method m that you would decorate.

Here’s an example without using a decorator and by using staticmethod() instead:

class Coffee:

  def __init__(self, milk, beans):
    self.milk = milk # percentage
    self.coffee = 100-milk # percentage
    self.beans = beans


  def __repr__(self):
    return f'Milk={self.milk}% Coffee={self.coffee}% Beans={self.beans}'


  def cappuccino():
    return Coffee(80, 'Arrabica')

  cappuccino = staticmethod(cappuccino)

print(Coffee.cappuccino())

The output is the same:

Milk=80% Coffee=20% Beans=Arrabica

However, this is not the recommended way—use a decorator with the @ annotation instead!

Related Article: Decorators

Static Method vs Instance Method

If you don’t use the @staticmethod annotator, you obtain an instance method per default. The instance method requires that the first argument self is a reference to the instance itself on which the method is called. The static method doesn’t pass any implicit argument. Thus, the difference between static methods and instance methods is that Python passes nothing in the first case while passing the instance (object) as a first implicit argument in the second case.

Here’s a minimal example of a static and an instance method:

class C:

    @staticmethod
    def f():
        print('hi')


    # instance method
    def g(self):
        None



# call static method:
C.f()

# call instance method:
C().g()

Static Method vs Class Method

You may know static methods from programming languages such as C++ or Java. They’re methods that exist independently of whether or not you created an instance of the class. That’s why they don’t use any instance variable in the method body. If you want to use a static method in Python, you need to use the @staticmethod annotation rather than the @classmethod annotation. The difference is that static methods don’t expect a reference to either the instance or the class as an implied first argument.

Here’s an example comparing class methods, instance methods, and static methods:

class C:

    @classmethod
    def f(cls):
        None


    # instance method
    def g(self):
        None


    @staticmethod
    def h():
        None


# call class method:
C.f()

# call instance method:
C().g()


# call static method:
C.h()

Static Method vs Class Method vs Instance Method

To summarize, here’s the difference between the three different types of methods:

  • Static Methods,
  • Class Methods, and
  • Instance Methods.
Instance MethodClass MethodStatic Method
Definitiondef f(self, arg1, arg2): ...def f(cls, arg1, arg2): ...def f(arg1, arg2): ...
First ArgumentReference to InstanceReference to ClassNo Reference
UsageOn instance: C().f(arg1, arg2)On class: C.f(arg1, arg2)On class: C.f(arg1, arg2)
ApplicationWork on data of specific instanceWork independently of instance data—but depends on class (e.g., factory).Work independent of instance data and class data (e.g., general computation)

Related Video: Python Class Method

Summary

Static methods are special cases of class methods. They’re bound to a class rather than an instance, so they’re independent on any instance’s state.

Python’s built-in function staticmethod() prefixes a method definition as an annotation @staticmethod. This annotation transforms a normal instance method into a static method.


Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!