Dav*_*ave 6 python django memory-management python-3.x
我正在使用 Python 3.7 和 Django。我正在读关于__slots__. 显然,__slots__可以通过提前列出所有对象属性来优化大量此类对象的内存分配。
class MyClass(object):
__slots__ = ['name', 'identifier']
def __init__(self, name, identifier):
self.name = name
self.identifier = identifier
self.set_up()
Run Code Online (Sandbox Code Playgroud)
我可能很明显的问题是为什么我们不想对所有对象都这样做?使用有什么缺点吗__slots__?
Luciano Ramalho的Fluent Python列出了以下注意事项
\n\n\n\n\xe2\x80\xa2 您必须记住在每个子类中重新声明
\n\n__slots__,因为\n 继承的属性会被解释器忽略。\xe2\x80\xa2 实例将只能具有 中列出的属性
\n\n__slots__,除非您将其包含__dict__在__slots__\xe2\x80\x94 中,但这样做可能会抵消内存节省。\xe2\x80\xa2 实例不能成为弱引用的目标,除非您\n 记得包含
\n__weakref__在__slots__.
| 归档时间: |
|
| 查看次数: |
1981 次 |
| 最近记录: |