Re: __methods__

Guido.van.Rossum@cwi.nl
Thu, 02 Feb 1995 18:42:19 +0100

> I had gotten so used to using "__methods__" on an object to see what
> you can do with it I'd forgotten that this isn't really built-in to
> the language but is a convention used by built-in types.
[Long spiel about implementing this for classes omitted.]

A few points.

- Why isn't this built in? Because you can easily write it in Python;
unlike built-in objects' methods, for which there is no other way to
find them.

- Why is the type of a method 'function' while inside the class
definition but 'instance method' when accessed through an instance?
Because there's special magic in an instance's "getattr"
implementation which, when it finds a function in the class, converts
it into an instance method. An instance method is just a tuple
containing a pointer to the function and a pointer to the instance.
If you access the same name through its class, there's similar
magic in the class's "getattr" which builds an "unbound method".

Some more tips: the (undocumented) standard module newdir.py contains
code that lists the methods of class instances -- including recursing
up the class inheritance tree. You could provide a standard
implementation of __methods__ by using a base class with a __getattr__
methoed that recognizes this attribute name and does the right thing.

--Guido van Rossum, CWI, Amsterdam <mailto:Guido.van.Rossum@cwi.nl>
<http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>