Distinguishing attributes and methods

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sat Dec 8 13:55:20 EST 2007


tjhnson at gmail.com a écrit :
> Hi,
> 
> 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.

Documentation.

>  With ipython, I
> use tab completion all the time, but I can rarely tell from the names
> alone whether it is an attribute or method.

Actually, in Python, what you call "methods" are technically attributes 
- usually class attributes, instances of the function class - until they 
are looked up, at which time the lookup mechanism detect that they 
implement the descriptor protocol, invoke it, an return the result of 
this invocation - here a 'method' instance - in place of the original 
attribute.

> Tips? Ideas? Best practices?

Reading the doc ?-)

Else, you can check whether the attribute is an instance of 
types.MethodType - but that's not 100% garanteed to work (someone could 
implement it's own descriptor type acting like a function but not 
returning a method object).

Or if all you need to know is if the attribute is callable, then just ask:

   print callable(obj.attr)

My 2 cents



More information about the Python-list mailing list