Python defines class methods

Source: Internet
Author: User

Similar to attributes, methods are also divided into instance methods and class methods .

All defined in class are instance methods, and the first argument of the instance method is the instance itself.

To define a class method in class, you need to write this:

class Person (object): Count = 0  @classmethod  def how_many (CLS): Return Cls.count def __init__ (self, name): Self.name = name Person.count = Per Son.count + 1print person.how_many () p1 = person (' Bob ') print person.how_many () 

By marking a @classmethod, the method binds to the person class, not to an instance of the class. The first parameter of the class method is passed into the class itself, usually named the parameter name CLS, and the above Cls.count is actually equivalent to person.count.

because it is called on a class and not on an instance, the class method cannot get any instance variables , you can only get a reference to the class.

Task

If you change the class attribute count to private property __count, the external cannot read __score, but can be obtained through a class method, write the class method to get the __count value.

? What's going on?

Note that class methods need to be added @classmethod

Reference code:

class Person (object):    __count = 0    @classmethod    def how_many (CLS):        return Cls.__count    def __init__ (self, name):        self.name = name        Person.__count = person.__count + 1print person.how_many () p1 = person ( ' Bob ') print Person.how_many ()

Python defines 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.