Python 特有的?什么是 slot

2015-01-15 15:02:59 +08:00
 vJianZhen

看这个Python文档的这部分: https://docs.python.org/3/library/stdtypes.html#typeiter

里面关于迭代器类型,有几个地方提到了slot这个东西:

1.This method corresponds to the tp_iter slot of the type structure for Python objects in the Python/C API.
2.This method corresponds to the tp_iter slot of the type structure for Python objects in the Python/C API.
3.This method corresponds to the tp_iternext slot of the type structure for Python objects in the Python/C API.

就是每个方法讲完,最后都有这么一句。那么这些句子怎么理解,特别是slot是什么东西!求解释或相关资料。

谷歌之后也没找到答案。

5290 次点击
所在节点    Python
11 条回复
mengzhuo
2015-01-15 15:09:01 +08:00
slot
指定以后 就不能添加其他attr
最大的作用是省内存
vJianZhen
2015-01-15 15:10:45 +08:00
@mengzhuo 属于类的么,那么Python/C API有tp_iter、tp_iternext 这两个对象?
BiggerLonger
2015-01-15 15:16:25 +08:00
当一个类指定了__slot__的时候, 由这个类实例化的对象将不会存在__dict__这个属性, 因此对象无法添加删除属性, 而由于对象少了__dict__属性, 在需要创建大量的这样的对象的时候, 会节省不少内存.
vJianZhen
2015-01-15 15:27:58 +08:00
@BiggerLonger 你说的的确讲得通。但是放在这几句话里还是觉得很违和,不知道该怎么理解这几句话
ruoyu0088
2015-01-15 15:54:36 +08:00
vJianZhen
2015-01-15 16:23:52 +08:00
@ruoyu0088 在这里,slot 是字段的意思?
bjzhush
2015-01-15 16:34:33 +08:00
既然有人正好问到这个问题,我求指教下.
py2.7中,slot不生效,不知道是我写的有问题还是什么问题呢..
code:

class Rog():
__slots__ = ('name', 'age')
pass

r = Rog()
r.xxx = 'xxxval'
print r.xxx

执行结果
zs@zsLinux:~/python$ python /tmp/x.py
xxxval

python版本
zs@zsLinux:~/python$ python
Python 2.7.3 (default, Feb 27 2014, 19:58:35)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

求指教,为什么slot不生效呢?
skybr
2015-01-15 16:44:35 +08:00
@bjzhush __slots__是针对new-style class, 你没继承object, 生成的是old-style class
pheyer
2015-01-15 16:46:55 +08:00
QT里面好像也有一个东东叫slot
bjzhush
2015-01-15 17:09:28 +08:00
@skybr 感谢指出
washinriver
2015-01-15 17:13:30 +08:00
楼上几位说的挺清楚了,我再贴个网上的例子,用slot以减少9g内存空间。
http://tech.oyster.com/save-ram-with-python-slots/

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/162413

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX