使用__slots__有缺点吗?

问题描述 投票:1回答:1

我正在使用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__有缺点吗?

python django python-3.x memory-management
1个回答
1
投票

Luciano Ramalho的Fluent Python列出了以下警告

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

•实例只能在__slots__中列出属性,除非你在__dict__中包含__slots__ - 但这样做可能会减少内存节省。

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

© www.soinside.com 2019 - 2024. All rights reserved.