static methods and member methods are loaded into objects of type Staticmethod and Classmethod, respectively, when they are created. The definition of a static method does not have a self parameter and can be called directly by the class itself, where the class method requires a parameter that is called CLS-like, which can be called directly from the class's specific object. But the CLS parameter is automatically bound to the class, see the following example:
1 __metaclass__=type2 3 classMyclass:4 5 defSmeth ():6 Print "This is a static method"7Smeth =Staticmethod (Smeth)8 9 defCmeth (CLS):Ten Print "This is a class method of", the CLS OneCmeth = Classmethod (Cmeth)
Techniques for manual packaging and replacement methods look a bit monotonous. In Python2.4, a new syntax called adorners (decorators) is introduced for such packaging methods (it can wrap any callable object, which can be used for methods as well as functions). Use the @ operator to list adorners above a method (or function) to specify one or more adorners (the order in which multiple adorners are applied is the opposite of the specified order)
1 __metaclass__=type2 3 classMyclass:4 5 @staticmethod6 defSmeth ():7 Print "This is a static method"8 9 @classmethodTen defCmeth (CLS): One Print "This is a class method of"Cls
once these methods have been defined, they can be used as in the following example (No instantiation of the class in the example):>>>myclass.smeth ()This is a static method
>>>myclass.cmeth ()This is a class method of <class ' __main__. Myclass ' >
Static methods and class member methods (Python)