Static methods and class member methods (Python)

Source: Internet
Author: User

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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.