鍍金池/ 教程/ Python/ <code>__slots__</code>魔法
<code>open</code>函數(shù)
Python 2系列版本
可迭代對象(Iterable)
異常
在函數(shù)中嵌入裝飾器
你的第一個裝飾器
上下文管理器(Context managers)
<code>set</code>(集合)數(shù)據(jù)結(jié)構(gòu)
裝飾器類
字典推導式(<code>dict</code> comprehensions)
<code>Reduce</code>
捐贈名單
<code>Filter</code>
<code>try/else</code>從句
*args 的用法
<code>dir</code>
處理異常
<code>else</code>從句
對象自省
For - Else
18. 一行式
Python 3.2及以后版本
Global和Return
基于類的實現(xiàn)
容器(<code>Collections</code>)
23. 協(xié)程
推薦閱讀
譯者后記
<code>*args</code> 和 <code>**kwargs</code>
**kwargs 的用法
生成器(Generators)
迭代(Iteration)
基于生成器的實現(xiàn)
將函數(shù)作為參數(shù)傳給另一個函數(shù)
日志(Logging)
三元運算符
<code>inspect</code>模塊
枚舉
Map,F(xiàn)ilter 和 Reduce
各種推導式(comprehensions)
從函數(shù)中返回函數(shù)
列表推導式(<code>list</code> comprehensions)
處理多個異常
帶參數(shù)的裝飾器
對象變動(Mutation)
22. 目標Python2+3
迭代器(Iterator)
虛擬環(huán)境(virtualenv)
<code>__slots__</code>魔法
什么時候使用它們?
Python/C API
<code>Map</code>
SWIG
授權(quán)(Authorization)
裝飾器
一切皆對象
使用C擴展
使用 <code>*args</code> 和 <code>**kwargs</code> 來調(diào)用函數(shù)
17. <code>lambda</code>表達式
集合推導式(<code>set</code> comprehensions)
<code>type</code>和<code>id</code>
在函數(shù)中定義函數(shù)
<code>finally</code>從句
CTypes
調(diào)試(Debugging)
使用場景
生成器(Generators)
多個return值
關于原作者
函數(shù)緩存 (Function caching)
Python進階

<code>__slots__</code>魔法

在Python中,每個類都有實例屬性。默認情況下Python用一個字典來保存一個對象的實例屬性。這非常有用,因為它允許我們在運行時去設置任意的新屬性。

然而,對于有著已知屬性的小類來說,它可能是個瓶頸。這個字典浪費了很多內(nèi)存。Python不能在對象創(chuàng)建時直接分配一個固定量的內(nèi)存來保存所有的屬性。因此如果你創(chuàng)建許多對象(我指的是成千上萬個),它會消耗掉很多內(nèi)存。
不過還是有一個方法來規(guī)避這個問題。這個方法需要使用__slots__來告訴Python不要使用字典,而且只給一個固定集合的屬性分配空間。

這里是一個使用與不使用__slots__的例子:

  • 不使用 __slots__:

    class MyClass(object):
      def __init__(self, name, identifier):
          self.name = name
          self.identifier = identifier
          self.set_up()
      # ...
  • 使用 __slots__:
    class MyClass(object):
      __slots__ = ['name', 'identifier']
      def __init__(self, name, identifier):
          self.name = name
          self.identifier = identifier
          self.set_up()
      # ...

第二段代碼會為你的內(nèi)存減輕負擔。通過這個技巧,有些人已經(jīng)看到內(nèi)存占用率幾乎40%~50%的減少。

稍微備注一下,你也許需要試一下PyPy。它已經(jīng)默認地做了所有這些優(yōu)化。

以下你可以看到一個例子,它用IPython來展示在有與沒有__slots__情況下的精確內(nèi)存占用,感謝 https://github.com/ianozsvald/ipython_memory_usage

Python 3.4.3 (default, Jun  6 2015, 13:32:34)
Type "copyright", "credits" or "license" for more information.

IPython 4.0.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import ipython_memory_usage.ipython_memory_usage as imu

In [2]: imu.start_watching_memory()
In [2] used 0.0000 MiB RAM in 5.31s, peaked 0.00 MiB above current, total RAM usage 15.57 MiB

In [3]: %cat slots.py
class MyClass(object):
        __slots__ = ['name', 'identifier']
        def __init__(self, name, identifier):
                self.name = name
                self.identifier = identifier

num = 1024*256
x = [MyClass(1,1) for i in range(num)]
In [3] used 0.2305 MiB RAM in 0.12s, peaked 0.00 MiB above current, total RAM usage 15.80 MiB

In [4]: from slots import *
In [4] used 9.3008 MiB RAM in 0.72s, peaked 0.00 MiB above current, total RAM usage 25.10 MiB

In [5]: %cat noslots.py
class MyClass(object):
        def __init__(self, name, identifier):
                self.name = name
                self.identifier = identifier

num = 1024*256
x = [MyClass(1,1) for i in range(num)]
In [5] used 0.1758 MiB RAM in 0.12s, peaked 0.00 MiB above current, total RAM usage 25.28 MiB

In [6]: from noslots import *
In [6] used 22.6680 MiB RAM in 0.80s, peaked 0.00 MiB above current, total RAM usage 47.95 MiB