Python uses `staticmethod` to define a static method

Document 对象参考手册Python3 Examples

In Python,staticmethodis a decorator used to define a static method. Static methods do not depend on class instances or the class itself. They are typically used to perform operations related to the class but not dependent on class or instance state.

The following is an example usingstaticmethodto define 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 explanation:

  1. @staticmethodis a decorator used to mark themy_static_methodmethod as a static method.
  2. my_static_methodmethod does not acceptselforclsparameters, because it does not depend on the class instance or the class itself.
  3. Static methods can be called directly through the class name without creating an instance of the class.

Output:

This is a static method.

Document 对象参考手册Python3 Examples

Other extensions