python advanced five (custom class) [5-7 python in __slots__]

python in __slots__

Because Python is a dynamic language, any instance can dynamically add attributes at runtime.

To limit the properties added, e.g., Student class only allowed to add name, gender, and score these three attributes, you can use a special __slots__ implemented in Python.

As the name suggests, __slots__ is a class attribute refers to the allowed list :

1 class Student(object):
2     __slots__ = ('name', 'gender', 'score')
3     def __init__(self, name, gender, score):
4         self.name = name
5         self.gender = gender
6         self.score = score

Now, for instance operation:

1 >>> s = Student('Bob', 'male', 59)
2 >>> s.name = 'Tim' # OK
3 >>> s.score = 99 # OK
4 >>> s.grade = 'A'
5 Traceback (most recent call last):
6   ...
7 AttributeError: 'Student' object has no attribute 'grade'

__slots__ is selected to limit the current class has attributes that can, if not add any dynamic properties using __slots__ can save memory.

task

Assuming that defines the Person class by name and gender __slots__, please continue to add score defined by __slots__ in a derived class Student in the Student class can implement name, gender, and score 3 attributes.

 1 class Person(object):
 2 
 3     __slots__ = ('name', 'gender')
 4 
 5     def __init__(self, name, gender):
 6         self.name = name
 7         self.gender = gender
 8 
 9 class Student(Person):
10 
11     __slots__ = ('score',)
12 
13     def __init__(self, name, gender, score):
14         super(Student,self).__init__(name,gender)
15         self.score = score
16 
17 s = Student('Bob', 'male', 59)
18 s.name = 'Tim'
19 s.score = 99
20 print s.score

 

Guess you like

Origin www.cnblogs.com/ucasljq/p/11626781.html