在YouTube 上的Raymond Hettingers心理游戏中:
class Validator:
def __set_name__(self, owner, name):
self.private_name = f'_{name}'
def __get__(self, obj, objtype=None):
return getattr(obj, self.private_name)
def __set__(self, obj, value):
self.validate(value)
setattr(obj, self.private_name, value)
Daw-Ran Liou 在用 Python 3.6+ 编写描述符中指出:
[...] 我们需要直接访问dict对象,而不是使用内置函数 getattr 和 setattr,因为内置函数也会被描述符协议拦截并导致 RecursionError。
class Validator:
def __set_name__(self, owner, name):
self.name= name
def __get__(self, obj, objtype=None):
return obj.__dict__[self.name]
def __set__(self, obj, value):
self.validate(value)
obj.__dict__[self.name] = value
但 Matthew Egans在 YouTube 上描述描述符时说:
from weakref import WeakKeyDictionary
class Validator:
def __init__(self):
self.data = WeakKeyDictionary()
def __get__(self, obj, owner):
return self.data[obj]
def __set__(self, obj, value):
self.validate(value)
self.data[obj] = value
实现描述符的正确方法是什么?