PYTHON__ Basics: Class Properties, class methods, static methods

Source: Internet
Author: User

class properties are defined in the class, and the properties outside the method generally belong to this class, as the following NUM is the Class property:

class Test:     0

Class attributes are used for instance. class properties or Class. Class properties are accessible,

such as a = Test () can be accessed with a.num, but if the instance has an instance property Self.num then this access is actually self.num,

So the general use of the class. property is such Test.num access

class methods, which are methods that belong to this class, are defined in front of the adorner @classmethod and the first parameter passes the name of the current class, which is almost the same as self, but is generally represented by a CLS:

class Test:     0     @classmethod    def setnum (CLS, newnum):        = Newnum

This setnum method is the class method, which can be changed to 100 for the Class property num by calling Test.setnum (100).

Of course, it can be called by instance. Setnum (100), but if an instance method is also the name of test, then the invocation will be an instance method instead of a class method.

static methods : If a method, and the Class attribute instance property class method instance method has nothing to do with it, such as just print a word, then you can use him as a static method, before the need to add adorner @staticmethod:

class Test:    @staticmethod    def printinfo ():        print ('This isa staticmethod ')

This static method, like a class method, can be called with an instance or class, but it is generally used with classes. Static method calls, because if there is an instance method with the same name, the instance method is also preferred.

Python__ Basics: Class Properties, class methods, static methods

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.