Tag: Cal Call Limit add nbsp Ace Pre Attribute Property
__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 allowed properties for a class: Class Student (object): __slots__ = (' name ', ' gender ', ' score ') def __init__ (self, Name, gender, score): self.name = name Self.gender = gender Self.score = score Now, operate on the instance:>>> s = Stu Dent (' Bob ', ' Male ', ') >>> s.name = ' Tim ' # ok>>> s.score = # ok>>> s.grade = ' A ' Traceback ( Most recent call last): ... Attributeerror: ' Student ' object has no attribute ' grade ' __slots__ in order to limit the properties that the current class can have, and if you do not need to add any dynamic properties, using __slots__ can also save memory.
class Person (object): __slots__ = (' name ', ' Gender ') def __init__ (self, Name, gender): self.name = name Self.gender = Genderclass Student (person): __slots__ = (' score ',) def __init__ (Self,name,gender,score): Super (Student,self). __init__ (name,gender) self.score=scores = Student (' Bob ', ' Male ',) s.name = ' Tim ' S.score = 99print S.score
Class properties for Python-qualified class properties: __slots__