Q22: What is the purpose of the Python __slots__ attribute in classes, and how does it impact memory usage and attribute access?
A22:
Purpose of
__slots__Attribute:- The
__slots__attribute in Python is used to define a fixed set of attributes for a class. It restricts the creation of new attributes beyond those specified, providing a more memory-efficient representation for instances of the class.
- The
Impact on Memory Usage and Attribute Access:
- Memory Usage: Instances of a class with
__slots__use less memory because the interpreter allocates space only for the specified attributes, avoiding the overhead of a dynamic dictionary for attribute storage. - Attribute Access: Access to attributes is generally faster with
__slots__since it avoids the dictionary lookup for attribute names.
__slots__ is used to define that instances of the Person class can only have the attributes name and age. Attempting to assign the city attribute raises an AttributeError.
ไม่มีความคิดเห็น:
แสดงความคิดเห็น