Python staticmethod() built-in function

From the Python 3 documentation

Transform a method into a static method.

Introduction

The @staticmethod decorator transforms a method so that it belongs to a class but does not receive the class or instance as the first argument. This is useful for creating utility functions that have a logical connection to a class but do not depend on class or instance state.

A static method can be called either on the class itself or on an instance.

Example

Here is how you define and call a static method:

class MathHelper:
    @staticmethod
    def add(x, y):
        return x + y

# Call on the class
result1 = MathHelper.add(5, 3)
print(result1)

# Call on an instance
helper = MathHelper()
result2 = helper.add(10, 20)
print(result2)
8
30

A static method does not have access to the class (cls) or the instance (self). It’s essentially a regular function namespaced within the class.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.