Skip to content

Latest commit

 

History

History
53 lines (44 loc) · 1.5 KB

File metadata and controls

53 lines (44 loc) · 1.5 KB
title Python staticmethod() built-in function - Python Cheatsheet
description Transform a method into a static method.
Python staticmethod() built-in function From the Python 3 documentation Transform a method into a static method. The @staticmethod is a function decorator that will transform a class method into a static method that functions in a similar behavior to a C++ or other oop language static methods.

You can turn a class method into a static method by applying the @staticmethod decorator to a function in a class. For example:

>>> class C:
>>>    @staticmethod
>>>    def function(): ....

Static methods can be called on the class itself like

>>> class Class:
>>>    @staticmethod
>>>    def function():
>>>        print("X")
>>>
>>> Class.function()
>>> # X

Or on an instance of the class like

>>> class Class:
>>>    @staticmethod
>>>    def function():
>>>        print("X")
>>>
>>> new_class = Class()
>>> new_class.function()
>>> # X

The @staticmethod is in the form of a decorator the basics being it is a function that will return another function. This will be documented at a later time.