As you know, when you create an instance of a class, you can add attributes to the instance, and __slots__ 's role is to limit what properties we can add and write a simple example.
Class Student (object):
__slots__= (' name ', ' age ')
S=student ()
S.name= ' Mr.xu '
S.age=22
S.core=30
Running results we get an error:attributeerror: ' Student ' object has no attribute ' score ' hint we don't have score this property, the result is, Name is the age these two attributes were added, and score was rejected
This time we will create a student subclass Student2
Class Student2 (Student):
Pass
S2=student2 ()
S2.name= ' Mr.Lee '
s2.score=100
S2.age=22
Print (S2.name,s2.age,s2.score)
Run the result as
Mr.xu 22 100
As can be seen, although we inherited the student class, but did not inherit his __slots__ variable, we can add any attribute to the Student2 instance, then we will define a __slots__ variable for Student2 to see
Class Student2 (Student):
__slots__= (' Grade ')
S2=student2 ()
S2.name= ' Mr.xu '
Print (S2.name)
S2.age=22
Print (S2.age)
s2.score=100
Print (S2.score)
S2.grade= ' Freshman '
Print (S2.grade)
Here, we have added the __slots__ variable value to the Student2 class to grade, and added the grade attribute to the instance s2
Let's look at the result of running the results separately:
S2.name= ' Mr.xu '
Print (S2.name)
Mr.xu
---------------------------------
S2.age=22
Print (S2.age)
22
---------------------------------
s2.score=100
Print (S2.score)
Attributeerror: ' Student2 ' object has no attribute ' score '
---------------------------------
S2.grade= ' Freshman '
Print (S2.grade)
Freshman
Grade,name,age three attributes were added successfully, except score, because if the subclass defines the __slots__ variable, then he is allowed to create his own (STUDENT2) __slots__ variable and its parent class (Student).
The __slots__ variable. A subclass (Student2) instance (S2) allows creation (' Grade ', ' name ', ' age ') three properties
Application of Python object-oriented __slots__ variable