[3-5] Advanced Python class method definitions

The method defined in class python

And similar properties, a method can be divided into class and instance method method.

Defined in the class are all examples of the method, the first parameter instance method is self instance itself.

To define class methods class, need to write:

class Person(object):
    count = 0
    @classmethod
    def how_many(cls):
        return cls.count
    def __init__(self, name):
        self.name = name
        Person.count = Person.count + 1

print Person.how_many()
p1 = Person('Bob')
print Person.how_many()

By a marker @classmethod, the method binds to the Person class, example, and not class. The first parameter of the incoming class methods class itself, usually the name of the parameter named cls, above cls.count actually equivalent Person.count.

Because it is in the class calls rather than calling on the instance, therefore Class methods can not get any instance variables, can only obtain a reference to the class.

task:

If the class attribute count changed to private property __count, the outside can not read __score, but you can get through a class method, write a class method to obtain __count value.

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 + 1

print Person.how_many()
p1 = Person('Bob')
print Person.how_many()
Published 20 original articles · won praise 0 · Views 388

Guess you like

Origin blog.csdn.net/yipyuenkay/article/details/104500453