0

在实现描述符时,可以使用__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']

是否有一种简洁通用的方法可以知道从哪个属性访问了描述符?

4

1 回答 1

2

是否有一种简洁通用的方法可以知道从哪个属性访问了描述符?

不,没有干净和通用的方法。

但是,如果您想要一个肮脏的 hack(请不要这样做!)您可以避免使用描述符协议,而只需传入手动访问它的名称:

class Descriptor:
    def __get__(self, instance, owner, name=None):
        print(f"Property was accessed through {name}")
        return 'foo'

p = Descriptor()

class Test:
    a = p
    b = p

    def __getattribute__(self, name):
        for klass in type(self).__mro__:
            if name in klass.__dict__ and isinstance(klass.__dict__[name], Descriptor):
                return klass.__dict__[name].__get__(self, klass, name)
        else:
            return object.__getattribute__(self, name)
于 2018-06-13T15:44:09.717 回答