วันอาทิตย์ที่ 18 กุมภาพันธ์ พ.ศ. 2567

What is the purpose of the Python __slots__ attribute in classes, and how does it impact memory usage and attribute access?

 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.
  • 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.
# Example of using __slots__
class Person:
    __slots__ = ('name', 'age')

# Creating an instance with __slots__
person = Person()
person.name = 'Alice'
person.age = 30

# This would raise an AttributeError
person.city = 'Wonderland'

In this example, __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.

ไม่มีความคิดเห็น:

แสดงความคิดเห็น

How does the Python Global Interpreter Lock (GIL) impact the performance of multi-threaded programs, and what strategies can be employed to mitigate its effects?

  Q10: How does the Python Global Interpreter Lock (GIL) impact the performance of multi-threaded programs, and what strategies can be emplo...