[Python-Dev] Issue10403 - using 'attributes' instead of members in documentation
Steven D'Aprano
steve at pearwood.info
Tue Jun 28 15:20:34 CEST 2011
Michael Foord wrote:
> What do you mean by "instances can have methods as instance attributes"?
> Once you attach a bound method directly to an instance it becomes a
> slightly different beast I think. (On top of which that is pretty rare
> behaviour.)
>>> class C:
... def method(self, x):
... return x+1
...
>>> c = C()
>>> c.method = types.MethodType(lambda self, x: x+101, c)
>>> c.method(1)
102
I don't know how rare it is, but it's a useful trick for customising the
behaviour of instances.
As I see it, there are three dichotomies we sometimes need to make:
(1) Instance attributes vs class (shared) attributes.
Broadly speaking, whether the attribute is in instance.__dict__ or
type(instance).__dict__.
(2) Computed vs non-computed attributes.
Attributes which are computed by __getattr__ or via the descriptor
protocol (which includes properties) are all computed attributes;
everything else is non-computed.
(3) Method attributes (methods) vs non-method/data attributes.
Broadly speaking, methods are callable, non-method (data) attributes are
not.
The three are orthogonal: e.g. a staticmethod is a method by virtue of
being callable, computed by virtue of being generated by a descriptor,
and a class attribute by virtue of existing in the type __dict__ rather
than the instance __dict__.
Strictly speaking, (3) is not truly a dichotomy, since functions and
methods are first class-objects in Python. E.g. one may store a function
as an attribute with the intention of using it as data rather than as a
method. But that's a moderately obscure corner case, and in my opinion
it's not worth obscuring the practical distinction between "methods are
things you call, data are not" for the sake of it. Leave the
functions-as-data case for a footnote.
--
Steven
More information about the Python-Dev
mailing list