WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Python · Advanced · question 55 of 100

What is the role of Python’s slots attribute in classes? How does it improve memory usage and performance?

📕 Buy this interview preparation book: 100 Python questions & answers — PDF + EPUB for $5

In Python, each object has an associated dictionary that stores the object’s attributes. This dictionary can be accessed using the __dict__ attribute. However, for objects that have a fixed set of attributes, this dictionary can be a waste of memory.

This is where the __slots__ attribute comes in. It is a class-level attribute that allows you to explicitly define the attributes that an object can have. By doing so, you can avoid the creation of the __dict__ attribute, which can lead to significant memory savings, especially when creating many instances of the same class.

Here’s an example:

    class Person:
        __slots__ = ['name', 'age']
        
        def __init__(self, name, age):
            self.name = name
            self.age = age

In this example, we define a Person class with two attributes, name and age. By setting __slots__ to a list of these two attributes, we tell Python that instances of this class should only have these two attributes and not any other.

The benefits of using __slots__ are twofold: first, it can significantly reduce the memory footprint of your code, especially when creating many instances of the same class. Second, it can also improve the performance of your code, since accessing attributes that are defined using __slots__ is faster than accessing attributes stored in the __dict__ dictionary.

However, it’s important to note that __slots__ has some limitations. For example, you cannot dynamically add new attributes to instances of a class that uses __slots__. Additionally, you cannot use inheritance with classes that use __slots__ unless the child class also defines the same __slots__ attribute as the parent class.

Overall, __slots__ can be a useful tool for optimizing the memory usage and performance of your Python code, but it should be used judiciously and with an understanding of its limitations.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Python interview — then scores it.
📞 Practice Python — free 15 min
📕 Buy this interview preparation book: 100 Python questions & answers — PDF + EPUB for $5

All 100 Python questions · All topics