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 self
variables:
class Student(object): def __init__(self, name): self.name = name s = Student('Bob') s.score = 90
But what if Student
the class itself needs to bind a property? Attributes can be defined directly in the class. This attribute is a class attribute and is Student
classified 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() #Create an instance s >>> print (s.name) #Print the name attribute, because the instance does not have a name attribute, it will continue to look for the name attribute of the class Student >>> print (Student.name ) #Print the name attribute of the class Student >>> s.name = ' Michael ' #Bind the name attribute to the instance >>> print (s.name) #Because the instance attribute has a higher priority than the class attribute, it will be blocked Drop the name attribute of the class Michael >>> print (Student.name) #But the class attribute has not disappeared, and Student.name can still be used to access Student >>> del s.name #If you delete the name attribute of the instance >>> print(s.name) #Call s.name again . Since the name attribute of the instance is not found, the name attribute of the class is displayed as 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.
practise
In order to count the number of students, you can add a class attribute to the Student class. Each time you create an instance, the attribute will automatically increase:
class Student(object): count = 0 def __init__(self, name): self.name = name #Test : if Student.count != 0: print ( ' Test failed! ' ) else : bart = Student( ' Bart ' ) if Student.count != 1 : print ( ' Test failed! ' ) else : lisa = Student( ' Bart ' ) if Student.count != 2 : print ( ' Test failed! ' ) else : print ( ' Students: ' , Student.count) print ( ' Test passed! ' )
Answer
class Student(object): count = 0 def __init__(self, name): self.name = name Student.count +=1 #Test : if Student.count != 0: print ( ' Test failed! ' ) else : bart = Student('Bart1') if Student.count != 1: print(Student.count) print('测试失败!!') else: lisa = Student( ' Bart2 ' ) if Student.count != 2 : print (Student.count) print ( ' Test failed!!! ' ) else : print ( ' Students: ' , Student.count) print ( ' Test passed ! ' ) #Output Students : 2 tests passed!