Looking up an attribute of Describe instance 1 from a Client instance or a Client class requires knowing its specific attribute name (i.e. value). Either way, both lookups return the same exact value because they accessed the same attribute to begin with. Encapsulation does not exist here.

But what if you want to control access to the attributes of the Describe instance such that you can control what exact values are returned based on whether the lookup was via the instance object or via the class?

Here you don’t even need to know the specific attribute name. The Descriptor class takes care of that for you. Proper encapsulation exists here, as it should.

Very important note: For it to work, descriptor objects MUST be a class attribute within the client.

__get__(self, instance, owner)

  • instance is the object we wish to encapsulate
  • owner essentially means class (i.e. the class of the instance object)

Descriptor’s __get__ method is that mechanism where you can influence what gets returned or gets processed from a member instance lookup.

__set__(self, instance, value)

The __set__ method is where you can influence processing or validation of the values right before assigning it to a property. 2

Here we use that descriptor behavior to validate the input values.

If it’s not within the range of the required value then it doesn’t proceed.

  1. client.desc [return]
  2. It gets called right about when you assign something to the descriptor object. [return]