python进阶五(定制类)【5-7 python中__slots__】

python中 __slots__

由于Python是动态语言,任何实例在运行期都可以动态地添加属性。

如果要限制添加的属性,例如,Student类只允许添加 name、gender和score 这3个属性,就可以利用Python的一个特殊的__slots__来实现。

顾名思义,__slots__是指一个类允许的属性列表

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

现在,对实例进行操作:

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__的目的是限制当前类所能拥有的属性,如果不需要添加任意动态的属性,使用__slots__也能节省内存。

任务

假设Person类通过__slots__定义了name和gender,请在派生类Student中通过__slots__继续添加score的定义,使Student类可以实现name、gender和score 3个属性。

 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

 

posted on 2019-10-06 11:14  ucas_python  阅读(228)  评论(0编辑  收藏  举报