192. Descriptor Chaining

1. Basic Descriptor

  • A simple descriptor controlling attribute access.

class UpperCaseDescriptor:
    def __get__(self, instance, owner):
        return instance.__dict__.get("_name", "").upper()
    
    def __set__(self, instance, value):
        instance.__dict__["_name"] = value

class Person:
    name = UpperCaseDescriptor()  # Using the descriptor

p = Person()
p.name = "alice"
print(p.name)  # Output: ALICE

🔍 How it works:

  • The descriptor automatically converts name to uppercase when accessed.


2. Chaining Two Descriptors

  • Combining two descriptors to control access.

🔍 How it works:

  • The last assigned descriptor (UpperCaseDescriptor) takes precedence.


3. Combining Read-Only and Validation Descriptors

  • Using two descriptors: one for validation and one for read-only access.

🔍 How it works:

  • ValidateLength first validates the input.

  • ReadOnly then prevents modification.


4. Logging Access with a Descriptor

  • Logs access before returning the attribute.

🔍 How it works:

  • Logs every read and write operation.


5. Using Property with Descriptors

  • Combining property() with a descriptor.

🔍 How it works:

  • property() is used along with the Capitalize descriptor.


Last updated