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

Explain the concept of Python's data descriptor and how it differs from a non-data descriptor. Provide an example to illustrate their usage.

 Q28: Explain the concept of Python's data descriptor and how it differs from a non-data descriptor. Provide an example to illustrate their usage.

A28:

  • Data Descriptor in Python:

    • A data descriptor is an object that defines methods such as __get__, __set__, or __delete__ and is intended for managing how attributes are accessed, assigned, or deleted.
  • Difference from Non-Data Descriptor:

    • Data descriptors have both __get__ and __set__ methods, making them suitable for attributes that can be both read and modified. Non-data descriptors only have __get__, making them suitable for read-only attributes.
    class DataDescriptor: def __get__(self, instance, owner): print(f"Getting value: {instance._value}") return instance._value def __set__(self, instance, value): print(f"Setting value: {value}") instance._value = value class MyClass: def __init__(self, value): self._value = value descriptor_attr = DataDescriptor() # Using the data descriptor obj = MyClass(42) obj.descriptor_attr # Calls __get__ obj.descriptor_attr = 100 # Calls __set__

    In this example, DataDescriptor is a data descriptor assigned to the descriptor_attr attribute of the MyClass instances. When accessed or modified, the descriptor's __get__ or __set__ methods are invoked accordingly.

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

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

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...