在前文《【笔记】python面向对象-类和实例(详述类和实例属性和方法的绑定)》的数据封装那节写过如何给类和实例动态绑定属性和方法。那如果我们想要限制实例的属性怎么办?比如,只允许对Student实例添加name
和age
属性。
在定义class的时候,定义一个特殊的__slots__
变量,来限制该class实例能添加的属性。
目录
__slots__
@property
练习
__slots__
接收一个元组,元组中的字符串表示的属性为允许添加的属性。如果添加了未被允许的属性会触发AttributeError。
class Student(object):
... __slots__ = ('name','age')
...
... stu1 = Student()
... stu1.name = 'forst'
... stu1.age = 23
... stu1.high = 165
Traceback (most recent call last):File "<input>", line 7, in <module>
AttributeError: 'Student' object has no attribute 'high'
注意:仅对当前类实例起作用,对继承的子类是不起作用
class Student(object):
... __slots__ = ('name','age')
...
... class Grupe(Student):
... pass
...
... gru1 = Grupe()
... gru1.num = 12
... print(gru1.num)
12
我们在定义类的时候,由于有些属性很可能不是直接暴露的,需要通过getter和setter方法(此外还有deleter)来实现对这些属性的读取和设置等操作。但是设置两个独立的函数又显得比较笨,而通过@property装饰器可以将getter和setter方法变成一个属性调用,这样我们在访问这些实例的属性的时候好像是直接操作的属性一样。总的来说,property是一个装饰器,可以把方法变成属性调用。注意getter和setter方法的函数名字一定要一样!property方法非常了类似C++的函数重载,看下边的例子
class Student(object):@propertydef score(self):return self._score@score.setterdef score(self, value):if not isinstance(value, int):raise ValueError('score must be an integer!')if value < 0 or value > 100:raise ValueError('score must between 0 ~ 100!')self._score = valuestu1=Student
stu1.score = 10
print(stu1.score)
使用方法如下:
在getter方法前加上@property,此时就会以这个getter方法的名字创建一个setter装饰器,把这个setter装饰器加在setter方法前面即可。如果只定义getter方法而不定义setter方法的话则这个属性是只读的。
请利用@property
给一个Screen
对象加上width
和height
属性,以及一个只读属性resolution
class Screen(object):@propertydef width(self):return self._width@width.setterdef width(self,value1):if not isinstance(value1,int):raise ValueError('width must be int type')if value1 <= 0:raise ValueError('width should >0')self._width = value1@propertydef height(self):return self._height@height.setterdef height(self,value):if not isinstance(value,int):raise ValueError('height must be int type')if value <= 0:raise ValueError('height should >0')self._height = value@propertydef resolution(self):return self._height*self._widths = Screen()
s.width = 1024
s.height = 768
print('resolution =', s.resolution)
solution == 786432:print('测试通过!')
else:print('测试失败!')
本文发布于:2024-01-31 04:42:54,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170664737725577.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |