python防止随意修改类属性的实现方法
作者:zx 时间:2021-07-16 00:34:40
如果不想允许随意修改一个类的某个属性,常用的方法是使用property装饰器以及在属性前加下划线。
class V:
def __init__(self, x):
self._x = x
@property
def x(self):
return self._x
虽然这样是没法直接修改x了,但还是可以通过_x很轻易地修改x。
>>>v = V(5)
>>>v.x
5
>>>v._x
5
>>>v.x = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: cant set attribute
>>>v._x = 4
>>>v.x
4
万一哪天手抖了呢...
但如果使用双下划线——
class V:
def __init__(self,x):
self.__x = x
@property
def x(self):
return self.__x
>>>v = V(5)
>>>v.__x = 4
>>>v.__x
4
>>>v.x
5
原因在于python的名称改写特性(name mangling)。python会将以双下划线开头的实例属性名前加上一个下划线和类名存入实例的__dict__属性中。
>>>v = V(5)
>>>v.__dict__
{'_V__x': 5}
>>>v.__x = 4
>>>v.__dict__
{'_V__x': 5, '__x': 4}
当然,修改v.x的值还是可以做到的的,只需通过修改v._V__x就可以了,不过误操作的可能性已经降低很多了。
p.s.类也有__dict__属性。
来源:https://segmentfault.com/a/1190000020134064
标签:python,类属性
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python中的十大图像处理工具(小结)
2021-02-04 09:17:51
![](https://img.aspxhome.com/file/2023/2/82612_0s.jpg)
网站防止采集方法全攻略
2007-09-05 19:57:00
Django开发的简易留言板案例详解
2022-05-05 00:24:40
![](https://img.aspxhome.com/file/2023/5/85055_0s.png)
js 实现数值的千分位及保存小数方法(推荐)
2023-08-17 01:13:11
Django Admin中增加导出CSV功能过程解析
2021-04-17 06:22:47
![](https://img.aspxhome.com/file/2023/1/115781_0s.jpg)
Oracle PL/SQL入门案例实践
2010-07-18 13:13:00
Python之文字转图片方法
2022-02-12 07:11:10
![](https://img.aspxhome.com/file/2023/6/115826_0s.jpg)
浅析Python打包时包含静态文件处理方法
2023-05-29 01:12:10
CSS 的优先规则
2009-01-08 12:40:00
pygame游戏之旅 如何制作游戏障碍
2021-03-05 00:16:28
![](https://img.aspxhome.com/file/2023/7/87757_0s.png)
jQuery在去除缓存数据的一个失误
2009-12-14 20:40:00
msxml3.dll 错误 ‘800c0005’解决方案
2009-10-05 18:36:00
python产生模拟数据faker库的使用详解
2022-05-25 22:43:35
Python实现KNN(K-近邻)算法的示例代码
2023-09-25 15:56:18
![](https://img.aspxhome.com/file/2023/7/83957_0s.png)
Oracle与SQL Server数据库镜像对比
2009-03-25 14:27:00
JS target与currentTarget区别说明
2023-08-22 20:14:40
抛砖引玉Web2.0设计指南
2008-06-30 12:49:00
![](https://img.aspxhome.com/file/UploadPic/up/2008063013584749.gif)
Anaconda+Pycharm+Pytorch虚拟环境创建(各种包安装保姆级教学)
2023-06-27 23:21:39
![](https://img.aspxhome.com/file/2023/9/85139_0s.png)
python实现Oracle查询分组的方法示例
2021-03-30 10:59:54
javascript实现日期3级联动下拉框选择菜单
2023-10-19 02:15:34