我很困惑为什么在实例实例化之后检索或在实例构造期间设置的实例属性是通过描述符完成的。
例如,假设我们有以下描述符和类。
描述符
from weakref import WeakKeyDictionary
class Positive:
def __init__(self):
self._instance_data = WeakKeyDictionary()
def __get__(self, instance, owner):
return self._instance_data[instance]
def __set__(self, instance, value):
if value <= 0:
raise ValueError(f'Value {value} is not positive')
self._instance_data[instance] = value
def __delete__(self, instance):
raise AttributeError('Cannot delete attribute!')
班级
class Planet:
def __init__(self, name, mass_kilograms):
self.name = name
self.mass_kilograms= mass_kilograms
mass_kilograms = Positive()
现在我们创建一个 Planet 实例并检索它的质量。
pluto = Planet(name = 'Pluto', mass_kilograms = 1.305e22)
# The above line is doing Positive.__set__(self, pluto, 1.305e22) under the hood.
# It is NOT doing self.mass_kilograms = 1.305e22. In fact, all of the instance
# attributes are stored in the descriptor Positive's _instance_data
m = pluto.mass_kilograms # m = Positive.__get__(self, pluto, Planet)
我不知道为什么Positive.__get__
要调用它,因为它是一个类属性。有人可以解释一下吗?更令人困惑的是如何Positive.__set__
拦截构造函数参数的直接赋值mass_kilograms
。
谢谢!