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