class Student(object): __slots__ = ('name', 'age')
然后,我们试试:
>>> s = Student() # 创建新的实例 >>> s.name = 'Michael' # 绑定属性'name' >>> s.age = 25 # 绑定属性'age' >>> s.score = 99 # 绑定属性'score' Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Student' object has no attribute 'score'
由于'score'
没有被放到__slots__
中,所以不能绑定score
属性,试图绑定score
将得到AttributeError
的错误。
使用__slots__
要注意,__slots__
定义的属性仅对当前类实例起作用,对继承的子类是不起作用的:
>>> class GraduateStudent(Student): ... pass ... >>> g = GraduateStudent() >>> g.score = 9999
除非在子类中也定义__slots__
,这样,子类实例允许定义的属性就是自身的__slots__
加上父类的__slots__
二、@property和setter
使用装饰器设置getter和setter
练习:
请利用
@property
给一个Screen
对象加上width
和height
属性,以及一个只读属性resolution
:
class Screen(object): @property def width(self): return self._width @property def height(self): return self._height @width.setter def width(self, value): self._width = value @height.setter def height(self, value): self._height = value @property def resolution(self): return self._height * self._width s = Screen() s.width = 1024 s.height = 768 print('resolution =', s.resolution) if s.resolution == 786432: print('测试通过!') else: print('测试失败!')