Python practical notes (22) object-oriented programming - instance attributes and class attributes

Since Python is a dynamic language, instances created from classes can have arbitrary binding properties.

The way to bind properties to an instance is through instance variables, or through selfvariables:

class Student(object):
    def __init__(self, name): self.name = name s = Student('Bob') s.score = 90 

But what if Studentthe class itself needs to bind a property? Attributes can be defined directly in the class. This attribute is a class attribute and is Studentclassified all:

class Student(object):
    name = 'Student' 

When we define a class attribute, although this attribute is classified as all, all instances of the class can be accessed. Let's test it out:

>>> class Student(object): ... name = 'Student' ... >>> s = Student() # 创建实例s >>> print(s.name) # 打印name属性,因为实例并没有name属性,所以会继续查找class的name属性 Student >>> print(Student.name) # 打印类的name属性 Student >>> s.name = 'Michael' # 给实例绑定name属性 >>> print(s.name) # 由于实例属性优先级比类属性高,因此,它会屏蔽掉类的name属性 Michael >>> print(Student.name) # 但是类属性并未消失,用Student.name仍然可以访问 Student >>> del s.name # 如果删除实例的name属性 >>> print(s.name) # 再次调用s.name,由于实例的name属性没有找到,类的name属性就显示出来了 Student 

As can be seen from the above example, when writing a program, do not use the same name for instance attributes and class attributes, because instance attributes with the same name will block the class attributes, but after you delete the instance attributes, use The same name, the access will be the class property.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325946497&siteId=291194637