Why property works only for objects?

Alex Martelli aleaxit at yahoo.com
Sat Mar 11 04:10:24 CET 2006

Michal Kwiatkowski <ruby at no.spam> wrote:
> I'm trying to understand attributes lookups made by Python, having
> properties and special methods in mind. So far I've come up with kind of
>  reasoning I've coded below. I would appreciate any comments and
> suggestions.

First, let's forget legacy-style classes, existing only for backwards
compatibility, and focus on new-style ones exclusively -- never use
legacy classes if you can avoid that.

Descriptors come in two varieties: overriding and non-overriding. Both
kinds have a __get__ method (that's what makes them descriptors).
Overriding ones also have a __set__, non-overriding ones don't. (Until
pretty recently, the two kinds were known as data and non-data, but the
new terminology of overriding and non-overriding is much clearer).

I covered descriptors in one of my talks at Pycon '05 and elsewhere; you
can find just about all of my talks by starting at www.aleax.it (mostly
just PDF forms of the slides in my presentations). I cover them in quite
a central role in the forthcoming 2nd edition of Python in a Nutshell,
too. But, summarizing:

overriding descriptors are FIRST looked up in the class (class overrides
instance); non-overriding descriptors, first in the instance (class does
not override).  Functions are NON-overriding descriptors.

Special methods IMPLICITLY looked up by Python ALWAYS go to the class
ONLY -- adding an x.__getitem__ per-class attribute that happens to be
callable doesn't mean that attribute is gonna handle z=x[y] and the like
(in legacy-style classes the rule was different, but that led to a host
of complications that we're much better off without!).


More information about the Python-list mailing list