data attributes override method attributes?

Thomas Rachel nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de
Tue Sep 25 15:52:23 EDT 2012


Am 25.09.2012 16:08 schrieb Peter Otten:
> Jayden wrote:
>
>> In the Python Tutorial, Section 9.4, it is said that
>>
>> "Data attributes override method attributes with the same name."
>
> The tutorial is wrong here. That should be
>
> "Instance attributes override class attributes with the same name."

I jump in here:

THere is one point to consider: if you work with descriptors, it makes a 
difference if they are "data descriptors" (define __set__ and/or 
__delete__) or "non-data descriptors" (define neither).

As http://docs.python.org/reference/datamodel.html#invoking-descriptors 
tells us, methods are non-data descriptors, so they can be overridden by 
instances.

OTOH, properties are data descriptors which cannot  be overridden by the 
instance.

So, to stick to the original example:

class TestDesc(object):
     def a(self): pass
     @property
     def b(self): print "trying to get value - return None"; return None
     @b.setter
     def b(self, v): print "value", v, "ignored."
     @b.deleter
     def b(self): print "delete called and ignored"


and now

 >>> t=TestDesc()
 >>> t.a
<bound method TestDesc.a of <__main__.TestDesc object at 0xb7387ccc>>
 >>> t.b
trying to get value - return None
 >>> t.a=12
 >>> t.b=12
value 12 ignored.
 >>> t.a
12
 >>> t.b
trying to get value - return None
 >>> del t.a
 >>> del t.b
delete called and ignored
 >>> t.a
<bound method TestDesc.a of <__main__.TestDesc object at 0xb7387ccc>>
 >>> t.b
trying to get value - return None


Thomas



More information about the Python-list mailing list