python数据描述符_用Python编写非数据描述符

您已成功创建了正确的非数据描述符,但随后通过设置实例属性来屏蔽d属性.

因为它是非数据描述符,所以实例属性在这种情况下获胜.添加__set__方法时,将描述符转换为数据描述符,即使存在实例属性,也始终应用数据描述符.

The default behavior for attribute access is to get, set, or delete the attribute from an object’s dictionary. For instance, a.x has a lookup chain starting with a.__dict__['x'], then type(a).__dict__['x'], and continuing through the base classes of type(a) excluding metaclasses. If the looked-up value is an object defining one of the descriptor methods, then Python may override the default behavior and invoke the descriptor method instead. Where this occurs in the precedence chain depends on which descriptor methods were defined.

If an object defines both __get__() and __set__(), it is considered a data descriptor. Descriptors that only define __get__() are called non-data descriptors (they are typically used for methods but other uses are possible).

Data and non-data descriptors differ in how overrides are calculated with respect to entries in an instance’s dictionary. If an instance’s dictionary has an entry with the same name as a data descriptor, the data descriptor takes precedence. If an instance’s dictionary has an entry with the same name as a non-data descriptor, the dictionary entry takes precedence.

如果删除d实例属性(从不设置它或从实例中删除它),则调用描述符对象:

>>> class D(object):

... def __init__(self, x = 1395):

... self.x = x

... def __get__(self, instance, owner):

... print "getting", self.x

... return self.x

...

>>> class C(object):

... d = D()

...

>>> c = C()

>>> c.d

getting 1395

1395

再次添加实例属性并忽略描述符,因为实例属性获胜:

>>> c.d = 42 # setting an instance attribute

>>> c.d

42

>>> del c.d # deleting it again

>>> c.d

getting 1395

1395

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值