为什么在定义为实例属性时不会调用描述符?

Aro*_*vit 10 python descriptor

当我将"data"变量设为类变量时,以下方法有效,但当我将其设为对象变量时,不会调用该描述符.请帮忙.

class Data(object):
    products = {
        'milk': {'price': 1.50, 'quantity': 10},
        'eggs': {'price': 0.20, 'quantity': 100},
        'cheese': {'price': 2.00, 'quantity': 10}
    }
    def __get__(self, obj, klas):
        print "Here in descriptor"
        return self.products

class BusinessLogic(object):
    def __init__(self):         # When I remove these 2 lines 
        self.data = Data()
    #data = Data()             # and enable this line it does work !

def main():
    b = BusinessLogic()
    b.data

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

Ash*_*ary 14

那是因为描述符只应该定义为类属性,而不是实例属性:

来自docs:

以下方法仅在包含该方法的类的实例(所谓的描述符类)出现在所有者类中时才适用(该描述符必须位于所有者的类字典中或其父类之一的类字典中).

要使描述符与实例属性一起工作,你需要覆盖.的__getattribute__方法BusinessLogic.(没有彻底测试过,但是对你的情况很好):

def __getattribute__(self, attr):
        obj = object.__getattribute__(self, attr)
        if hasattr(obj, '__get__'):
            return obj.__get__(self, type(self))
        return obj
Run Code Online (Sandbox Code Playgroud)

如果您有数据描述符,那么您还需要处理该__setattr__部分.

def __setattr__(self, attr, val):
    try:
        obj = object.__getattribute__(self, attr)
    except AttributeError:
        # This will be raised if we are setting the attribute for the first time
        # i.e inside `__init__` in your case.
        object.__setattr__(self, attr, val)
    else:
        if hasattr(obj, '__set__'):
            obj.__set__(self, val)
        else:
            object.__setattr__(self, attr, val)
Run Code Online (Sandbox Code Playgroud)