在实现描述符时,可以使用__set_name__
来注册描述符设置在哪个属性名称下。
虽然,假设我们要为同一个描述符设置多个属性,那么似乎无法知道在__get__
and__set__
方法中通过哪个名称访问描述符。
代码
class Prop:
def __init__(self):
self._names = {}
def __set_name__(self, owner, name):
print(f'Attribute \'{name}\' was set to a Prop')
if owner in self._names:
self._names[owner].append(name)
else:
self._names[owner] = [name]
def __get__(self, instance, owner):
print(f'Prop was accessed through one of those: {self._names[owner]}')
prop = Prop()
class Foo:
bar = prop
baz = prop
foo = Foo()
foo.baz
输出
Attribute 'bar' was set to a Prop
Attribute 'baz' was set to a Prop
Prop was accessed through one of those: ['bar', 'baz']
是否有一种简洁通用的方法可以知道从哪个属性访问了描述符?