Quick Tip: Use slots to reduce Python class memory usage
When creating classes in Python, you can significantly reduce memory usage by using the __slots__ attribute. Unlike regular classes, which store instance attributes in a dictionary (__dict__), __slots__ stores them in a tuple, resulting in less memory consumption.
Here's a minimal example:
python
import sys
class RegularClass:
def __init__(self, x, y):
self.x = x
self.y = y
class SlottedClass:
__slots__ = ('x', 'y')
def __init__(self, x, y):
self.x = x
self.y = y
#
---
*Follow me on Dev.to for daily Python tips and quick guides!*
---
喜欢这篇文章?关注获取更多Python自动化内容!
---
If you found this useful, you might like **[Python Automation Scripts Pack (10 Ready-to-Use Tools)](https://qssec.gumroad.com/l/python-automation-pack)** — a practical resource that takes things a step further. At $14.99 it's a solid investment for your toolkit.
Top comments (0)