Python class methods

Source: Internet
Author: User

Http://www.cnpythoner.com/post/308.htmlhttp://www.cnpythoner.com/post/308.html

These three words appear in the Python class, and the self and the CLS can be replaced by other words, and there are three methods of the class.

One is defined by Def, the ordinary general, need to pass at least one parameter, generally with self, such a method must be accessed through an instance of a class, similar to C + + through the object to access;

The second is to add @classmethod in front of Def, this kind of method is a feature that can be called by the class name, but also must pass a parameter, generally with the CLS to represent class, that can be called directly through the class;

The third is to add @staticmethod in front of Def, this class method is static class method, similar to C + + static function, one of his characteristics is that the parameter can be empty, also support the class name and object two kinds of call mode;

Code:

[Python] View plaincopy

class A:      member = "this is a test."      def __init__(self):          pass      @classmethod      def Print1(cls):          print "print 1: ", cls.member      def Print2(self):          print "print 2: ", self.member      @classmethod          def Print3(paraTest):          print "print 3: ", paraTest.member      @staticmethod      def print4():          print "hello"  a = A()  A.Print1()    a.Print1()  #A.Print2()  a.Print2()  A.Print3()  a.Print3()   

Python class methods

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.