python class attributes

The properties bound to an instance object belong to this instance only, and the properties bound to one instance will not affect other instances; similarly, classes can also bind properties, but the properties of the class do not belong to any object, but belong to this class. . If you bind a property to a class, all instances can access the properties of the class, and all instances access the same class property! In other words, each instance of the instance attribute has its own and independent of each other, while the class attribute has one and only one copy.
Access to class attributes Access to class attributes
through the class, when the instance does not have the same name as the class, you can still access the class attributes through the instance object

# Enter a code
## the first time to create a class 'Person'

class Person(object):
    count = 0
    def __init__(self, name, sex, age):
        self.name = name
        self.sex = sex
        self.age = age
        Person.count += 1
xiaoming = Person('xiaoming', 'M', 18)

xin = Person('xin', 'F', 18)

print(xiaoming.name, xiaoming.sex, xiaoming.age)
print(xin.name, xin.sex, xin.age)
print("the number of objects is %i" %(Person.count))

If the class attribute and the instance attribute have the same name, the instance attribute takes precedence over the class attribute.

It is not possible to modify the properties of a class through an instance. In fact, modifying a class property through an instance method only binds a corresponding instance property to the instance.

Guess you like

Origin blog.csdn.net/angelsweet/article/details/114536151