Home > Article > Backend Development > How to use static methods
Static methods and class methods are referenced in python2.2, and both classic and new-style classes can be used. At the same time, a pair of built-in functions: staticmethod and classmethod were introduced to convert a certain method in the class into one of these two methods.
Static method refers to a method in a class that can be called without the participation of an instance (no self parameter is required). During the calling process, there is no need to instantiate the class and is used directly after the class. Sign operator calls the method.
Normally, static methods are declared using the @staticmethod decorator.
Sample code:
class ClassA(object): @staticmethod def func_a(): print('Hello Python') if __name__ == '__main__': ClassA.func_a() # 也可以使用实例调用,但是不会将实例作为参数传入静态方法 ca = ClassA() ca.func_a()
It should be noted here that in Python 2, if a class method does not require a self parameter, it must be declared as a static method, that is, add the @staticmethod decorator , thus calling it without an instance.
In Python 3, if a class method does not require a self parameter, it no longer needs to be declared as a static method. However, in this case, the method can only be called through the class. If the method is called using an instance, it will cause abnormal.
class ClassA(object): def func_a(): print('Hello Python') if __name__ == '__main__': ClassA.func_a() # 以下使用实例调用会引发异常 ca = ClassA() ca.func_a()
Exception information:
func_a() takes 0 positional arguments but 1 was given
Because func_a is not declared as a static method, the class instance will be hidden when calling func_a The self parameter is passed into func_a, while func_a itself does not accept any parameters, thus throwing an exception.
The above is the detailed content of How to use static methods. For more information, please follow other related articles on the PHP Chinese website!