__slots__because Python is a dynamic language, any instance can dynamically add properties at run time. If you want to limit the properties that you add, for example, the student class only allows you to add the 3 properties of name, gender, and score, you can take advantage of a special __slots__ of Python. As the name implies,__slots__ refers to a list of properties allowed by a class:classStudent (object):__slots__= ('name','Gender','score') def __init__(self, name, gender, score): Self.name=name Self.gender=Gender Self.score=score now, take action on the instance:>>> s = Student ('Bob','male', 59)>>> S.name ='Tim' #OK>>> S.score = 99#OK>>> S.grade ='A'Traceback (most recent): ... Attributeerror:'Student'object has no attribute'Grade'The purpose of __slots__ is to limit the properties that the current class can have, using __slots__ can save memory if you don't need to add any dynamic properties.
classPerson (object):__slots__= ('name','Gender') def __init__(self, Name, gender): Self.name=name Self.gender=GenderclassStudent (person):__slots__= ('score',) def __init__(Self,name,gender,score): Super (student,self).__init__(name,gender) Self.score=scores= Student ('Bob','male', 59) S.name='Tim'S.score= 99PrintS.score
Class properties for Python-qualified class properties: __slots__