已知__slots__默认移除__dict__省内存,为何同时默认移除__weakref__?
__slots__ remove __weakref__ by default? Great question—this is one of those subtle Python details that made me scratch my head when I first started using __slots__ too. Let's break this down clearly:
First, a quick recap of what __slots__ does at its core: it lets you explicitly list the attributes an instance of your class can have. This replaces the per-instance __dict__—a dynamic hash table that normally lets you add arbitrary attributes to an instance on the fly. The big win here is memory savings, since each instance no longer carries the overhead of that extra hash table.
Now, onto the __weakref__ part:
- A
__weakref__is a special type of reference that lets you refer to an object without preventing it from being garbage collected. For Python to track weak references to an instance, the instance needs a dedicated internal slot to store metadata about those weak references. - When you don't use
__slots__, every instance automatically gets both a__dict__(for dynamic attributes) and a__weakref__slot. But when you switch to__slots__, Python's default behavior is to strip out all optional instance slots unless you explicitly include them. The goal here is maximum memory efficiency—if you don't need weak references for your instances, there's no reason to waste memory on that unused slot.
If you do need weak references for a class using __slots__, it's straightforward to get them back: just add '__weakref__' to your __slots__ definition, like this:
class MyClass: __slots__ = ['name', 'age', '__weakref__']
This fits right into Python's "explicit is better than implicit" philosophy—you only pay for the features you actually need, rather than carrying around unused baggage.
内容的提问来源于stack exchange,提问作者czheo

