DEV Community

qing
qing

Posted on • Edited on

Quick Tip: Use `__slots__` to reduce Python class memory usage (2026)

Quick Tip: Use slots to reduce Python class memory usage

When creating classes in Python, you may not be aware that each instance has a built-in dictionary called __dict__ that stores its attributes. This can lead to increased memory usage, especially when dealing with a large number of instances.

In contrast, using __slots__ allows you to explicitly declare the attributes of a class, which prevents the creation of __dict__ and __weakref__ for each instance. This results in significant memory savings.

Here's a minimal example:


python
import sys

class RegularClass:
    def __init__(self, x, y):
        self.x = x
        self.y = y

---

*Follow me on Dev.to for daily Python tips and quick guides!*

---

*🛠️ Useful resource: **Content Creator Ultimate Bundle (Save 33%)** — $29.99. Check it out on Gumroad!*

---
喜欢这篇文章?关注获取更多Python自动化内容!
Enter fullscreen mode Exit fullscreen mode

Top comments (0)