Python definition Class Method

Source: Internet
Author: User

Python definition Class Method

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

InClassAll defined in is the instance method, the first parameter of the instance methodSelfIs the instance itself.

To define class methods in class, you need to write the following 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()

By marking a @ classmethod, this method is boundPersonClass, rather than class instances. The first parameter of the class method will be passed into the class itself, usually namedCls, The aboveCls. countActually equivalentPerson. count.

Because it is called on a class rather than an instance, the class method cannot obtain any instance variables and can only obtain class references.

Task

If you set the class PropertyCountChange to private property_ Count, The external cannot be read._ ScoreBut it can be obtained through a class method. please compile the class method to obtain_ CountValue.

 

? No, what should I do?

Note that @ classmethod must be added to the class method.

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()

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.