192. Descriptor Chaining
1. Basic Descriptor
A simple descriptor controlling attribute access.
Copy
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
nameto uppercase when accessed.
2. Chaining Two Descriptors
Combining two descriptors to control access.
Copy
🔍 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.
Copy
🔍 How it works:
ValidateLengthfirst validates the input.ReadOnlythen prevents modification.
4. Logging Access with a Descriptor
Logs access before returning the attribute.
Copy
🔍 How it works:
Logs every read and write operation.
5. Using Property with Descriptors
Combining
property()with a descriptor.
Copy
🔍 How it works:
property()is used along with theCapitalizedescriptor.
Last updated