A descriptor is a class that has the following methods.
Method | Call timing |
---|---|
get(self,obj,type) | When retrieving attributes |
set(self,obj,value) | When setting attributes |
delete(self,obj) | When deleting an attribute |
Since it is a method different from special methods such as getattr and setattr, it is necessary to recognize it separately from the descriptor.
-Behaviors related to attribute operations can be cut out to another class (= attribute-related functions that span classes can be reused.) -Can define behavior that applies only to specific attributes. (getattr, setattr affects all attributes of that class)
There is a merit of rice bowl. Descriptors are also used behind properties, classes / static methods, super, and so on.
descriptor_basic.py
#Definition of descriptor
class LogProp:
def __init__(self,name): #1
self.name = name #1
#Processing when retrieving attributes
def __get__(self,obj,type): #2
prin(f'{self.name}:get') #2,6
return obj.__dict__[self.name] #2,4
#Processing when setting attributes
def __set__(self,obj,value) #3
prin(f'{self.name}:set{value}') #3,7
obj.__dict__[self.name] = value #3,5
class App:
#Definition of descriptor
title = LogProp('title') #8
if __name__ == '__main__':
app = App()
app.title = 'Self-study python' #9
print(app.title) #9
The descriptors define init, get, set. First, the init method (# 1) receives and stores the attribute name that is the target of the descriptor. This is the key information for passing values later.
And set (# 2), get (# 3) are the main methods for passing values. get and set receive the following information via arguments.
obj: Target instance type: Target class value: value passed
In this example, the value of the instance is obtained and referenced via dict. Since get and set take over the attribute operation of the instance, the acquisition and setting of the attribute value will be invalid if there is no acquisition or save operation of any value.
Minimize the description like # 4,5 in the code, and add additional operations when getting and setting. In this example, the result of acquisition and setting is output by print.
To associate a predefined descriptor with an attribute, use # 8. (This is the same way you write a property with a property function.)
You can confirm that the log is output at the timing when the title is set like # 9 in the code.
Self-study python Quoted from Chapter 11 Object-Oriented Syntax
Recommended Posts