Analyzing the principle and function of Python descriptors by examples

Time:2020-3-22

This article mainly introduces the principle and function of parsing Python descriptors through examples. In this article, the example code is introduced in detail, which has a certain reference value for your study or work. You can refer to the following for your friends

In essence, a descriptor is a class, but it defines the way to access the properties in another class. In other words, a class can delegate property management to a descriptor class.

The descriptor class is based on three special methods, in other words, the three methods make up the descriptor protocol:

  • __Set (self, obj, type = none): this method is called when the property is set.
  • __Get UU (self, obj, value): this method is called when the property is read.
  • __Delete (self, obj): this method is called when del is called on an attribute.

Among them, the descriptors that implement setter and getter methods are called data descriptors, otherwise, if only getter methods are implemented, they are called non data descriptors.

#Descriptor class
class revealAccess:
  def __init__(self, initval = None, name = 'var'):
    self.val = initval
    self.name = name
  def __get__(self, obj, objtype):
    print("Retrieving", self.name)
    return self.val
  def __set__(self, obj, val):
    print("updating", self.name)
    self.val = val

class myClass:
  x = revelAccess(10, 'var "x"')
  y = 5
m = myClass()
print(m.x)
m.x = 20
print(m.x)
print(m.y)

Retrieving var "x"
10
updating var "x"
Retrieving var "x"
20
5

If a property of a class has a data descriptor, every time you look up the property, you will call the \.
This method is called every time a del class object. Property (or delattr (class object, property)) statement is used.

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.