繁体   English   中英

使用 __slots__ 有什么缺点吗?

[英]Are there disadvantages of using __slots__?

我正在使用 Python 3.7 和 Django。 我正在阅读“_slots__” ——http : //book.pythontips.com/en/latest/slots__magic.html 显然,_slots可以通过这样做来优化大量这些对象的内存分配......

class MyClass(object):
    __slots__ = ['name', 'identifier']
    def __init__(self, name, identifier):
        self.name = name
        self.identifier = identifier
        self.set_up()

我可能很明显的问题是为什么我们不想对所有对象都这样做? 使用 _slots__ 有什么缺点吗?

Luciano Ramalho 的Fluent Python列出了以下注意事项

• 您必须记住在每个子类中重新声明__slots__ ,因为解释器会忽略继承的属性。

• 实例只能具有__slots__列出的属性,除非您在__slots__包含__dict__ — 但这样做可能会抵消内存节省。

• 实例不能成为弱引用的目标,除非您记得在__slots__包含__weakref__

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM