我正在使用 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()
我可能很明显的问题是为什么我们不想对所有对象都这样做?使用 __slots__ 有缺点吗?
请您参考如下方法:
Fluent Python Luciano Ramalho 列出了以下注意事项
• You must remember to redeclare
__slots__in each subclass, since the inherited attribute is ignored by the interpreter.• Instances will only be able to have the attributes listed in
__slots__, unless you include__dict__in__slots__— but doing so may negate the memory savings.• Instances cannot be targets of weak references unless you remember to include
__weakref__in__slots__.
