- 节省内存
By default Python uses a dict to store an object’s instance attributes. Which is usually fine, and it allows fully dynamic things like setting arbitrary new attributes at runtime.
However, for small classes that have a few fixed attributes known at “compile time”, the dict is a waste of RAM, and this makes a real difference when you’re creating a million of them. You can tell Python not to use a dict, and only allocate space for a fixed set of attributes, by settings slots on the class to a fixed list of attribute names
2.结论
在确定了类的属性固定的情况下,可以使用__slots__
来优化内存。
网友评论