staticmethod()
The built-in function staticmethod()
converts a method to a static method. The function to be converted is passed as a parameter and the static conversion of the method is returned.
This function has several applications, one use case is the generation of a new static method from an existing instance method. A static method differs from a class or instance method in that it can’t modify the class or instance. These methods serve to impose a tighter scope over a given functionality and are used to signal the design intention and use of the class.
Note: While use of this built-in function was common in older versions of Python, it is considered more Pythonic to use the @staticmethod decorator to define static methods.
Syntax
staticmethod(function)
Example 1
Use staticmethod()
to convert the print_welcome method in the Codecademy
class to a static method:
class Codecademy:def print_welcome(name):print("Welcome to...", name)# Converting to static methodCodecademy.print_welcome = staticmethod(Codecademy.print_welcome)# Calling as a static method by the classCodecademy.print_welcome("Codecademy")# Calling as a static method by the objectCodecademy().print_welcome("Codecademy")
Example 2
Use staticmethod()
to create a static method in Codecademy
class from an external function:
def print_hello():print("Hello, I'm not from the class")class Codecademy:#converting print_hello to a static function and assigning to a method in Codecademy classcodecademy_hello = staticmethod(print_hello)#calling codecademy_hello as a static methodCodecademy.codecademy_hello()
Example 3
Use staticmethod()
to create a static function from a method in the Codecademy
class and call the function on its own:
class Codecademy:def print_welcome(name):print("Welcome to...", name)# Converting to static methodnew_welcome = staticmethod(Codecademy.print_welcome)# Calling new_welcomenew_welcome("Codecademy")
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours