Python Data Science Jobs & Interviews
20.4K subscribers
188 photos
4 videos
25 files
326 links
Your go-to hub for Python and Data Science—featuring questions, answers, quizzes, and interview tips to sharpen your skills and boost your career in the data-driven world.

Admin: @Hussein_Sheikho
Download Telegram
What are the implications of using __slots__ in Python classes, and how can it affect memory usage, performance, and inheritance?

Answer:
Using __slots__ in Python classes allows you to explicitly declare the attributes a class can have, which reduces memory usage by preventing the creation of a dict__dict__ for each instance. This results in faster attribute access since attributes are stored in a fixed layout rather than a dictionary. However, __slots__ restricts the ability to add new attributes dynamically, disables certain fedictike __dict__ and __weakref__, and complicates multiple inheritance because of potential conflicts between slot definitions in parent classes.

For example:

class Point:
__slots__ = ['x', 'y']

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

p = Point(1, 2)
# p.z = 3 # This will raise an AttributeError

While `__slots__` improves memory efficiency—especially in classes with many instances—it must be used carefully, particularly when dealing with inheritance or when dynamic attribute assignment is needed.

#Python #AdvancedPython #MemoryOptimization #Performance #OOP #PythonInternals

By: @DataScienceQ 🚀