Distinguishing attributes and methods

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sat Dec 8 17:11:15 EST 2007


MonkeeSage a écrit :
> On Dec 8, 12:56 pm, Bruno Desthuilliers
> <bdesth.quelquech... at free.quelquepart.fr> wrote:
> 
>>MonkeeSage a écrit :
>>
>>
>>
>>
>>>On Dec 8, 2:10 am, Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote:
>>
>>>>On Fri, 07 Dec 2007 23:19:40 -0800, tjhnson wrote:
>>
>>>>>With properties, attributes and methods seem very similar.  I was
>>>>>wondering what techniques people use to give clues to end users as to
>>>>>which 'things' are methods and which are attributes.
>>
>>>>Methods are attributes.  So the decision is easy -- everything on an
>>>>object is an attribute.  ;-)
>>
>>>>Ciao,
>>>>       Marc 'BlackJack' Rintsch
>>
>>>I think he means callable attributes (methods) and non-callable
>>>attributes (variables).
>>
>>callable attributes are not necessarily methods, and are still
>>'variables' anyway.
> 
> 
> I think it muddies the water to say that a.a() and a.a are the same
> thing--obviously they are not.

Indeed. a.a yields the object bound to name 'a' in object a, while a.a() 
yields the value returned by calling the object bound to name 'a' in 
object a.

> In the common case, the first is a
> method,

Nope, it's the value returned by the call to a callable - remember that 
in Python, the parens are the call operator, so the expression a.a() 
evals to the value returned by the call to a.a - which is either the 
method object returned by the collaboration of the lookup mechanism and 
the descriptor protocol or any other possible callable object bound to 
that name or returned by the lookup mechanism for that name.

> and the second is a variable.

The second is whatever the lookup mechanism will yield for this name.

> Yes, you can do silly stuff,
> such that this rule will not hold, but in general it does. Or am I
> wrong?

You're wrong. Python's "methods" are thin wrappers around an instance 
(or class) and a function. These wrappers are "built" *at lookup time* 
by the __get__ method of the function object itself when it's looked up 
as an attribute of a class, thanks to the lookup mechanism and the 
descriptor protocol.

Now the fact that an attribute is callable doesn't make it a "method".

Also, anyone can implement it's own callable type that will act as a 
true function - that is, implement the descriptor protocol to return a 
wrapper around the instance or class and the callable - without 
necessarily yielding an instance of types.MethodType. This is all fairly 
trivial.

And note that none of the two above cases are necessarily "silly". 
Python exposes most of it's object model so you can hook into it and 
taylor it to your needs. This results in some constructs that may seem 
weird at first, but make sens once you understand them and learn to use 
them.



More information about the Python-list mailing list