Python learning-instance attributes and class attributes

Since Python is a dynamic language, the instance created by the class can be bound to any attributes.

The method of binding properties to an instance is through instance variables, or through self variables:

class Student(object):
	def __init__(self, name):
		self.name = name

s = Student('Bob')
s.score = 90

But what if the Student class itself needs to bind a property? You can define attributes directly in the class. This attribute is a class attribute and belongs to the Student class.

class Student(object):
	name = 'Student'

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

>>>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 the instance attribute and the class attribute , because the instance attribute with the same name will shield the class attribute, but when you delete the instance attribute, use With the same name, the access will be the class attribute.

Exercise

In order to count the number of students, you can add a class attribute to the Student class. Each time an instance is created, the attribute of this class is automatically increased:
thinking, at the beginning, write count+=1 directly under count, can you generate one every time? +1 for instance

class Student(object):
    count = 0
    count += 1

    def __init__(self, name):
        self.name = name
 
if __name__ == '__main__':
    print(Student.count)
    bart = Student('bart')
    print(Student.count)
    part = Student('part')
    print(Student.count)

输出结果:
1
1
1

Looking back, Student is a class attribute, and every time an instance is created, is it necessary to call the __init__ method of a class? correct! Every time the __init__ method is called, it is called to create an instance!

class Student(object):
	count = 0

	def __init__(self, name):
		self.name = name
		Student.count += 1 # 这里要用类名

summary

  • Instance attributes are unique to each instance and do not interfere with each other;
  • Class attributes belong to the class, and all instances share one attribute;
  • Don't use the same name for instance attributes and class attributes, otherwise it will cause hard-to-find errors.

Guess you like

Origin blog.csdn.net/qq_44787943/article/details/112535261