Python 当定义为实例属性时,为什么没有调用描述符?
当我将“data”变量设置为类变量时,下面的操作会起作用,但当我将其设置为对象变量时,不会调用描述符。请帮忙Python 当定义为实例属性时,为什么没有调用描述符?,python,descriptor,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} }
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()
这是因为描述符应仅定义为类属性,而不是实例属性: 发件人: 以下方法仅在类的实例 包含该方法(所谓的描述符类)的 owner类(描述符必须位于owner类中的任何一个 字典或其父母之一的类字典) 要使描述符也能与实例属性一起工作,您需要覆盖
BusinessLogic
的\uuuu getattribute\uuuu
方法(尚未对此进行彻底测试,但适用于您的情况):
如果您有一个数据描述符,那么您还需要处理\uuu setattr\uuu
部分
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)
这太棒了!谢谢你的回答,它真的帮助了我。
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)