Python staticmethod Explained
staticmethod is a decorator in Python used to declare a static method. Static methods are called on the instantiated object of a class instead of within the method of the instantiated object. They can be accessed by both the class and its instances without needing to pass the instance itself.
Here is how to use the staticmethod function:
- Declare a static method in a class using the staticmethod decorator.
class MyClass:
@staticmethod
def my_static_method():
# 静态方法的代码
pass
- Static methods can be called directly using the class name.
MyClass.my_static_method()
- Static methods can also be called through an instance of a class.
instance = MyClass()
instance.my_static_method()
It is important to note that static methods do not have the ability to access a class instance or class property, so they can only access the class’s static properties and other static methods. Static methods are independent of class instances and class properties, so they do not need to pass the instance itself and will not automatically pass the instance itself.