Python类中的魔法方法之 __slots__原理解析
作者:JasonMingHao 时间:2023-10-01 18:49:51
在类中每次实例化一个对象都会生产一个字典来保存一个对象的所有的实例属性,这样非常的有用处,可以使我们任意的去设置新的属性。
每次实例化一个对象python都会分配一个固定大小内存的字典来保存属性,如果对象很多的情况下会浪费内存空间。
可通过__slots__方法告诉python不要使用字典,而且只给一个固定集合的属性分配空间
class Foo(object):
__slots__ = ("x","y","z")
def __init__(self,x,y):
self.x = x
self.y = y
self.z = None
def tell_info(self,name):
return getattr(self,name)
c = Foo(10,20)
# 设置和获取__slots__中设置的可访问实例属性
print(c.tell_info("x")) # 结果:10
c.z=50
print(c.tell_info("z")) # 结果:50
# 设置一个不在__slots__中存在的属性,会报错
c.e = 70 # AttributeError: 'Foo' object has no attribute 'e'
# 访问对象.__dict__ 也会直接报错
print(c.__dict__) # AttributeError: 'Foo' object has no attribute '__dict__'
来源:https://blog.51cto.com/12643266/2432560
标签:python,类,方法,slots
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python数字图像处理环境安装与配置过程示例
2023-03-05 07:00:25
![](https://img.aspxhome.com/file/2023/0/110290_0s.png)
python 基于opencv 绘制图像轮廓
2023-07-11 05:47:54
![](https://img.aspxhome.com/file/2023/2/133452_0s.png)
python 使用值来排序一个字典的方法
2022-02-05 00:25:05
浅谈vue异步数据影响页面渲染
2024-04-30 10:45:19
![](https://img.aspxhome.com/file/2023/5/130055_0s.jpg)
使用python向MongoDB插入时间字段的操作
2021-05-21 06:54:19
4款Javascript放大镜特效脚本
2009-10-14 20:46:00
![](https://img.aspxhome.com/file/UploadPic/200910/14/javascript-9-7-6j-25s.jpg)
pandas DataFrame运算的实现
2021-06-02 21:08:22
![](https://img.aspxhome.com/file/2023/0/72230_0s.jpg)
python+pyqt实现右下角弹出框
2023-09-07 16:04:22
![](https://img.aspxhome.com/file/2023/7/120997_0s.jpg)
vue单向数据流的深入讲解
2024-04-10 13:48:33
![](https://img.aspxhome.com/file/2023/6/139686_0s.png)
python可视化大屏库big_screen示例详解
2021-10-16 14:32:39
![](https://img.aspxhome.com/file/2023/7/87487_0s.jpg)
结合Python的SimpleHTTPServer源码来解析socket通信
2021-09-05 23:30:27
![](https://img.aspxhome.com/file/2023/6/105046_0s.jpg)
MySQL中对于not in和minus使用的优化
2024-01-17 04:17:20
Tornado高并发处理方法实例代码
2022-10-13 15:30:07
Javascript showModalDialog两个窗体之间传值
2024-04-28 09:38:56
Django外键(ForeignKey)操作以及related_name的作用详解
2023-03-15 22:48:09
![](https://img.aspxhome.com/file/2023/6/125156_0s.png)
vue中watch监听器用法之deep、immediate、flush
2024-04-27 16:13:35
Python任务调度模块APScheduler使用
2021-08-23 05:45:44
![](https://img.aspxhome.com/file/2023/3/124233_0s.jpg)
spring boot 测试单元修改数据库不成功的解决
2024-01-21 00:20:14
![](https://img.aspxhome.com/file/2023/6/77166_0s.png)
js 分栏效果实现代码
2024-05-03 11:10:47
pytorch tensor int型除法出现的问题
2021-05-18 13:18:17
![](https://img.aspxhome.com/file/2023/5/121155_0s.jpg)