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.
- A data descriptor is an object that defines methods such as
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,
DataDescriptoris a data descriptor assigned to thedescriptor_attrattribute of theMyClassinstances. When accessed or modified, the descriptor's__get__or__set__methods are invoked accordingly.- Data descriptors have both
ไม่มีความคิดเห็น:
แสดงความคิดเห็น