LoginSignup
33
25

More than 5 years have passed since last update.

``__slots__``を使ってメモリを節約

Posted at

知らなかったのでメモ。

Pythonではデフォルトではオブジェクトのインスタンスの属性はdictを使って保存している。
この保存の仕方では、実行中に新たな属性を動的に設定できたりして良い。

だけど、少数の固定な属性を持つ小さなクラスを扱うときにはdictはメモリの無駄。
こういう時は__slots__に属性の名前を記述することでメモリを節約したほうが良い。

class Image(object):
    __slots__ = ['id', 'caption', 'url']

    def __init__(self, id, caption, url):
        self.id = id
        self.caption = caption
        self.url = url
        self._setup()

        # ... other methods ...

参考

33
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
33
25