I've noticed that the order of attribute lookup is inconsistent
when descriptor is used. property instance takes precedence of
instance attributes:
[color=blue][color=green][color=darkred]
>>> class A(object):[/color][/color][/color]
.... def _get_attr(self) :
.... return self._attr
.... attr = property(_get_a ttr)
....[color=blue][color=green][color=darkred]
>>> a=A()
>>> a.__dict__[/color][/color][/color]
{}[color=blue][color=green][color=darkred]
>>> a.__dict__['attr']=1
>>> a.__dict__[/color][/color][/color]
{'attr': 1}[color=blue][color=green][color=darkred]
>>> a.attr[/color][/color][/color]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in _get_attr
AttributeError: 'A' object has no attribute '_attr'
But it doesn't when I use custom class of descriptor:
[color=blue][color=green][color=darkred]
>>> class descr(object):[/color][/color][/color]
.... def __get__(self, inst, cls):
.... return inst._attr
....[color=blue][color=green][color=darkred]
>>> class B(object):[/color][/color][/color]
.... attr = descr()
....[color=blue][color=green][color=darkred]
>>> b=B()
>>> b.__dict__[/color][/color][/color]
{}[color=blue][color=green][color=darkred]
>>> b.__dict__['attr']=1
>>> b.__dict__[/color][/color][/color]
{'attr': 1}[color=blue][color=green][color=darkred]
>>> b.attr[/color][/color][/color]
1
Subclasses of property behave like property itself:
[color=blue][color=green][color=darkred]
>>> class descr2(property ):[/color][/color][/color]
.... def __get__(self, inst, cls):
.... return inst._attr
....[color=blue][color=green][color=darkred]
>>> class C(object):[/color][/color][/color]
.... attr = descr2()
....[color=blue][color=green][color=darkred]
>>> c=C()
>>> c.__dict__[/color][/color][/color]
{}[color=blue][color=green][color=darkred]
>>> c.__dict__['attr']=1
>>> c.__dict__[/color][/color][/color]
{'attr': 1}[color=blue][color=green][color=darkred]
>>> c.attr[/color][/color][/color]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in __get__
AttributeError: 'C' object has no attribute '_attr'
Is it an undocumented feature or I have to submit a bug report?
--
Denis S. Otkidach
http://www.python.ru/ [ru]
Comment