Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Define a Static Method with staticmethod

Python uses staticmethod Define a static method

Document Object Reference Manual Python3 Examples

In Python,staticmethod is a decorator used to define a static method. Static methods do not depend on an instance of the class, nor on the class itself. They are usually used to perform operations related to the class but independent of class or instance state.

Below is an example using staticmethod Example of defining a static method:

Example

class

MyClass:

   

@

staticmethod

   

def

my_static_method

(

)

:

       

return

"This is a static method."

Call the static method

result

=

MyClass.

my_static_method

(

)

print

(

result

)

Code analysis:

  1. @staticmethod is a decorator used to mark the my_static_method method as a static method.
  2. my_static_method The method does not receive a self or cls parameter because it does not depend on an instance of the class or on the class itself.
  3. A static method can be called directly through the class name without creating an instance of the class.

Output result:

This is a static method.

Document Object Reference Manual Python3 Examples