Curriculum
Python descriptors are objects that define how attribute access is handled in Python. They are used to customize the behavior of attributes, such as adding validation or computation logic to attribute access and modification.
Descriptors are defined using special methods, such as __get__
, __set__
, and __delete__
, which are called when the attribute is accessed or modified. These methods take the instance of the object being accessed, the class of the object, and the name of the attribute as arguments, and are responsible for defining the behavior of attribute access and modification.
Here is an example of how to define a descriptor in Python:
class UpperCase: def __get__(self, instance, owner): return instance._value.upper() def __set__(self, instance, value): instance._value = value.lower() class Name: def __init__(self, name): self._name = name name = UpperCase()
Â
In this example, we define a descriptor UpperCase
that converts the value of the attribute to uppercase when it is retrieved, and to lowercase when it is set. We then define a class Name
with a property name
, which uses the UpperCase
descriptor to handle attribute access and modification.
When we create an instance of Name
and access its name
property, the __get__
method of the UpperCase
descriptor is called, which returns the uppercase value of the _value
attribute of the instance. When we set the name
property to a new value, the __set__
method of the UpperCase
descriptor is called, which sets the lowercase value of the _value
attribute of the instance.
Here is an example of how to use the Name
class:
n = Name('John') print(n.name) # 'JOHN' n.name = 'Doe' print(n.name) # 'DOE'
In this example, we create an instance of Name
with a name of ‘John’, and use the name
property to retrieve and set its value. When we retrieve the value of name
, we get the uppercase value of ‘John’, which is ‘JOHN’. When we set the value of name
to ‘Doe’, it is converted to lowercase by the UpperCase
descriptor, and the value of _value
is set to ‘doe’. When we retrieve the value of name
again, we get the uppercase value of ‘doe’, which is ‘DOE’.
Descriptors are a powerful feature of Python that allows for customization of attribute access and modification. They can be used to add complex logic to attribute access, such as validation or computation, and can provide a more intuitive and robust interface for working with objects.