In a nutshell, a descriptor is a way to customize what happens when you reference an attribute on a model. Normally, Python just gets and sets values on attributes without any special processing. It’s just basic storage. Sometimes, however, you might want to do more. You might need to validate the value that’s being assigned to a value. You may want to retrieve a value and cache it for later use, so that future references don’t have all the overhead.
__get__(self, instance, owner)
:当value = obj.attr)
时被调用
__set__(self, instance, value)
:当obj.attr = 'value'
时被调用
__delete__(self, instance)
:当从object中删除attribute时被调用
import random
class Die(object):
def __init__(self, sides=6):
self.sides = sides
def __get__(self, instance, owner):
return int(random.random() * self.sides) + 1
class Game(object):
d6 = Die()
d10 = Die(sides=10)
d20 = Die(sides=20)
>>> Game.d6
5
>>> Game.d10
8
>>> Game.d20
19
>>> Game.d20
3
>>> game = Game()
>>> game.d20
12
参考
http://martyalchin.com/2007/nov/23/python-descriptors-part-1-of-2/
http://martyalchin.com/2007/nov/24/python-descriptors-part-2-of-2/