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