Python staticmethod()

Python staticmethod() is a special type of method that belongs to a class but doesn't need an instance of the class to be called. Unlike regular methods, static methods don't take the instance (self) an implicit first argument.
Table of Contents

Understanding Python staticmethod()

In Python, a static method is a method that belongs to a class rather than an instance of the class. Unlike regular instance methods, a static method doesn’t receive the instance (self) as an implicit first argument. It also doesn’t receive the class (cls) like a class method. Python staticmethod() is like regular functions defined within a class’s namespace. It is used to group logically related functions within a class without needing to operate on instances or the class itself. You can create a static method using @staticmethod decorator or staticmethod() function.

Syntax of Python staticmethod()

class MyClass:
    @staticmethod
    def my_static_method(arg1, arg2):
        # Method body

Explanation

  • class MyClass:: Defines a class named MyClass.
  • @staticmethod: Decorator marks the method my_static_method as static.
  • def my_static_method(arg1, arg2):: Defines the static method named my_static_method. It does not take self or cls as arguments.
  • arg1, arg2: Regular parameters that the static method can accept.
  • # Method body: This is where you write the code that the static method will execute.

Example of Python staticmethod()

class MyClass:
    @staticmethod
    def greet(name):
        print(f"Hello, {name}!")

MyClass.greet("World")

Explanation

  • class MyClass:: Defines a class named MyClass.
  • @staticmethod: Decorator marks the greet method as static.
  • def greet(name):: Defines the static method greet, which takes one argument name.
  • print(f"Hello, {name}!"): Prints a greeting using the provided name.
  • MyClass.greet("World"): Calls the static method greet directly on the class MyClass.

Output

Hello, World!


staticmethod() Parameters

A static method created using @staticmethod, does not take any special parameters like self or cls. It behaves like a regular function defined within a class. Python staticmethod() can accept any number of regular arguments, just like a normal function, but it won’t implicitly receive the instance of the class or the class itself when called. You must pass arguments to staticmethod() just like a regular function.

Syntax

class MyClass:
    @staticmethod
    def my_static_method(param1, param2, ...):
        # Method body

Example

class StringUtils:
    @staticmethod
    def to_uppercase(text):
        return text.upper()

result = StringUtils.to_uppercase("hello")
print(result)

Explanation

  • class StringUtils::Defines a class named StringUtils.
  • @staticmethod: Decorator marks to_uppercase as a static method.
  • def to_uppercase(text):: Defines the static method, taking a text argument.
  • return text.upper(): Converts the text to uppercase and returns it.
  • result = StringUtils.to_uppercase("hello"): Calls to_uppercase on the StringUtils class, storing the result in result.
  • print(result): Prints the value of result.

Output

HELLO


staticmethod() Return Type

A static method in Python can return any value, just like a regular function. The return type depends on what you’ve programmed the method to do. It could be a number, a string, a list, a boolean, an object of a custom class, or even None if you don’t explicitly return anything. Python staticmethod() does not have any restrictions for the return type.

Example

class Calculator:
    @staticmethod
    def multiply(x, y):
        return x * y

result = Calculator.multiply(5, 6)
print(result)

Explanation

  • class Calculator:: Defines a class named Calculator.
  • @staticmethod: Decorator marks multiply as a static method.
  • def multiply(x, y):: Defines the static method multiply, taking two arguments.
  • return x * y: Returns the product of x and y.
  • result = Calculator.multiply(5, 6): Calls multiply on the Calculator class, storing the result in result.
  • print(result): Prints the value of result.

Output

30


Create a Static Method Using staticmethod()

While the @staticmethod decorator is the most common way to create a static method, you can also use the built-in staticmethod() function to achieve the same result. You define a regular function within the class and then, outside the function definition, assign the function to a class variable using staticmethod() function with the function name as a parameter. This approach is less common but demonstrates that static methods are essentially regular functions associated with a class.

Syntax

class MyClass:
    def my_function(arg1, arg2):
        # Function body
    my_static_method = staticmethod(my_function)

Explanation

  • class MyClass:: Defines a class named MyClass.
  • def my_function(arg1, arg2):: Defines a regular function my_function within the class.
  • # Function body: This is where you write the code for the function.
  • my_static_method = staticmethod(my_function): Converts my_function into a static method using the staticmethod() function and assigns it to my_static_method.

Example

class MathOperations:
    def add(x, y):
        return x + y

    add_static = staticmethod(add)

result = MathOperations.add_static(3, 4)
print(result)

Explanation

  • class MathOperations:: Defines a class named MathOperations.
  • def add(x, y):: Defines a function add within the class.
  • return x + y: Returns the sum of x and y.
  • add_static = staticmethod(add): Converts add into a static method named add_static.
  • result = MathOperations.add_static(3, 4): Calls the static method add_static on MathOperations, storing the result.
  • print(result): Prints the value of result.

Output

7


staticmethod() Without Calling Instance

One of the key characteristics of a static method is that you can call it directly on the class itself, without needing to create an instance of the class. Python staticmethod() doesn’t depend on or interact with instance-specific data. You use the class name, followed by a dot (.), and then the name of the static method, along with any required arguments in parentheses.

Syntax

class MyClass:
    @staticmethod
    def my_static_method(arg1, arg2):
        # Method body

MyClass.my_static_method(val1, val2)

Explanation

  • class MyClass:: Defines a class named MyClass.
  • @staticmethod: Decorator marks my_static_method as static.
  • def my_static_method(arg1, arg2):: Defines the static method.
  • # Method body: This is where the static method’s code is written.
  • MyClass.my_static_method(val1, val2): Demonstrates calling the static method directly on the class MyClass without creating an object of that class.

Example

class StringHelper:
    @staticmethod
    def reverse_string(s):
        return s[::-1]

reversed_text = StringHelper.reverse_string("abcdef")
print(reversed_text)

Explanation

  • class StringHelper:: Defines a class named StringHelper.
  • @staticmethod: Decorator marks reverse_string as a static method.
  • def reverse_string(s):: Defines the static method, taking a string s as input.
  • return s[::-1]: Returns the reversed string.
  • reversed_text = StringHelper.reverse_string("abcdef"): Calls reverse_string directly on StringHelper without creating an instance and stores the returned value.
  • print(reversed_text): Prints the reversed string.

Output

fedcba


staticmethod() for Mathematical Operations

Static methods are often used to group related utility functions within a class, and mathematical operations are a common example. You can create a class that contains Python staticmethod() for various mathematical calculations, making it a convenient container for these functions. Static methods are a good fit since these operations typically don’t rely on instance-specific data.

Syntax

class MathUtils:
    @staticmethod
    def operation1(...):
        # Perform operation 1

    @staticmethod
    def operation2(...):
        # Perform operation 2

Explanation

  • class MathUtils:: Defines a class named MathUtils to hold mathematical utility functions.
  • @staticmethod: Decorator marks the following methods as static.
  • def operation1(...):: Defines a static method for a specific mathematical operation.
  • # Perform operation 1: This is where you’d write the code for the first operation.
  • def operation2(...):: Defines another static method for a different mathematical operation.
  • # Perform operation 2: This is where you’d write the code for the second operation.

Example

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

    @staticmethod
    def subtract(x, y):
        return x - y

sum_result = MathUtils.add(10, 5)
diff_result = MathUtils.subtract(10, 5)
print(f"Sum: {sum_result}, Difference: {diff_result}")

Explanation

  • class MathUtils:: Defines a class MathUtils to group math-related functions.
  • @staticmethod: Marks add and subtract as static methods.
  • def add(x, y):: Defines a static method add that returns the sum of x and y.
  • def subtract(x, y):: Defines a static method subtract that returns the difference between x and y.
  • sum_result = MathUtils.add(10, 5): Calls add to get the sum.
  • diff_result = MathUtils.subtract(10, 5): Calls subtract to get the difference.
  • print(f"Sum: {sum_result}, Difference: {diff_result}"): Prints the results.

Output

Sum: 15, Difference: 5


staticmethod() to Access Class Variables

Unlike class methods, static methods cannot directly access or modify class-level variables because they don’t receive the cls argument. However, they can access class variables indirectly using the class name. You can refer to class variables in the Python staticmethod() using ClassName.variable_name. This approach is useful when a static method needs to use a class-level variable in its calculations or operations without altering its value.

Syntax

class MyClass:
    class_variable = ...

    @staticmethod
    def my_static_method():
        # Access class_variable using MyClass.class_variable

Explanation

  • class MyClass:: Defines a class named MyClass.
  • class_variable = ...: Initializes a class-level variable.
  • @staticmethod: Decorator marks my_static_method as a static method.
  • def my_static_method():: Defines the static method.
  • # Access class_variable using MyClass.class_variable: Inside the method, you access the class variable using the class name MyClass.

Example

class Circle:
    pi = 3.14159

    @staticmethod
    def calculate_area(radius):
        return Circle.pi * radius * radius

area = Circle.calculate_area(5)
print(area)

Explanation

  • class Circle:: Defines a class named Circle.
  • pi = 3.14159: Initializes a class-level variable pi.
  • @staticmethod: Decorator marks calculate_area as a static method.
  • def calculate_area(radius):: Defines the static method calculate_area, which takes radius as input.
  • return Circle.pi * radius * radius: Calculates the area using the class variable pi.
  • area = Circle.calculate_area(5): Calls calculate_area on the Circle class to get the area for a radius of 5.
  • print(area): Prints the calculated area.

Output

78.53975


staticmethod() for String Formatting

Static methods can be useful for utility functions related to a class, such as string formatting. You might define a Python staticmethod within a class to provide a specific way to format strings related to that class, even if the formatting doesn’t depend on instance-specific data. This keeps the formatting logic within the class’s namespace, improving code organization.

Syntax

class MyClass:
    @staticmethod
    def format_string(...):
        # String formatting logic

Explanation

  • class MyClass:: Defines a class named MyClass.
  • @staticmethod: Decorator marks format_string as a static method.
  • def format_string(...):: Defines the static method responsible for string formatting.
  • # String formatting logic: This is where you write the code to format the string.

Example

class DateFormatter:
    @staticmethod
    def format_date(year, month, day):
        return f"{year}-{month:02}-{day:02}"

formatted_date = DateFormatter.format_date(2023, 5, 1)
print(formatted_date)

Explanation

  • class DateFormatter:: Defines a class named DateFormatter.
  • @staticmethod: Decorator marks format_date as a static method.
  • def format_date(year, month, day):: Defines the static method for formatting dates.
  • return f"{year}-{month:02}-{day:02}": Formats the date string, padding month and day with leading zeros if needed.
  • formatted_date = DateFormatter.format_date(2023, 5, 1): Calls the format_date method to format a date.
  • print(formatted_date): Prints the formatted date string.

Output

2023-05-01


Using the @staticmethod Decorator

The most common and recommended way to create a static method in Python is the @staticmethod decorator. You place this decorator immediately above the method definition within your class. This indicates that the method is static and doesn’t receive the instance (self) or the class (cls) as implicit first arguments. It makes your code more readable and easier to understand.

Example

class TemperatureConverter:
    @staticmethod
    def celsius_to_fahrenheit(celsius):
        return (celsius * 9/5) + 32

fahrenheit = TemperatureConverter.celsius_to_fahrenheit(25)
print(fahrenheit)

Explanation

  • class TemperatureConverter:: Defines a class named TemperatureConverter.
  • @staticmethod: Decorator marks celsius_to_fahrenheit as a static method.
  • def celsius_to_fahrenheit(celsius):: Defines the static method, taking celsius as input.
  • return (celsius * 9/5) + 32: Performs the Celsius to Fahrenheit conversion and returns the result.
  • fahrenheit = TemperatureConverter.celsius_to_fahrenheit(25): Calls the static method on the class to convert 25 Celsius to Fahrenheit.
  • print(fahrenheit): Prints the converted temperature.

Output

77.0


Using staticmethod() Function (Less Common)

While less common, you can use the built-in staticmethod() function to convert a regular function into a static method. You define the function within the class as usual, and then, outside the function definition, you reassign the function’s name to the result of calling staticmethod() on it. This approach is more verbose than using the @staticmethod decorator.

Example

class NumberChecker:
    def is_even(number):
        return number % 2 == 0

    check_even = staticmethod(is_even)

result = NumberChecker.check_even(6)
print(result)

Explanation

  • class NumberChecker:: Defines a class named NumberChecker.
  • def is_even(number):: Defines a function is_even within the class.
  • return number % 2 == 0: Returns True if the number is even, False otherwise.
  • check_even = staticmethod(is_even): Converts is_even into a static method named check_even.
  • result = NumberChecker.check_even(6): Calls the static method check_even on NumberChecker, storing the result.
  • print(result): Prints the result.

Output

True


Conclusion

Python staticmethod(), created using the @staticmethod decorator or the staticmethod() function, are methods that belong to a class but don’t operate on instances (self) or the class itself (cls). They are regular functions that are namespaced within a class for organizational purposes. Static methods are useful for utility functions, grouping related operations, and when you don’t need instance-specific or class-level data.

Understanding how Python staticmethod differs from the instance and class methods is key to writing well-structured, object-oriented Python code.


Also Read

Python enumerate()

Python filter()


Python Reference

python staticmethod()

Table of Contents