我正在使用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__
中列出属性,除非你在__dict__
中包含__slots__
- 但这样做可能会减少内存节省。•实例不能成为弱引用的目标,除非你记得在
__weakref__
中包含__slots__
。