如何从__get __中获取描述符的属性名称?

时间:2018-06-13 15:17:31

标签: python python-3.x python-descriptors

实现描述符时,可以使用__set_name__注册描述符所在的属性名称。

虽然,假设我们要为同一个描述符设置多个属性,但似乎无法知道在__get____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']

是否有一种干净而通用的方法来了解访问描述符的属性?

1 个答案:

答案 0 :(得分:2)

  

是否有一种干净而通用的方法来了解访问描述符的属性?

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

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

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)