To differentiate between them, write the following code:
1 classC:2 3 defSelf_method (Self, a):4 returna5 6 @classmethod7 defClass_method (CLS, a):8 returna9 Ten @staticmethod One defStatic_method (a): A returna - - defmethod (a): the returna - -if __name__ = = ' __main__ ': -c =C () + Print(C.self_method ('Self Method')) - Print(C.class_method ('class Method')) + Print(C.static_method ('static Method')) A #Print (C.method (' method ')) error running at #Print (C.self_method (' self method ')) error running - Print(C.class_method ('class Method')) - Print(C.static_method ('static Method')) - Print(C.method ('Method'))
So:
- When an instance method is defined, the first argument is an instance of the Class (self), which must be called through an instance when invoked. You can access instance properties and methods.
- Class methods use @classmethod decorations, the first parameter is a class (CLS), and can be called by an instance of the class or the class itself. You can access class properties and methods.
- Static methods use @staticmethod decorations, which can be invoked using an instance of the class or the class itself.
- The common method is to define a normal function in the class, which must be called by the class itself.
Example methods, class methods, static methods, and common methods in Python