[Tutor] dir() question: how do you know which are attributes and which are methods?

Gonçalo Rodrigues op73418@mail.telepac.pt
Sun May 25 20:59:01 2003


From: "R. Alan Monroe" <amonroe@columbus.rr.com>
> Subject says it all...
>
> example
>
>
> class dummy:
>         stuff = 0
>         def task():
>                 pass
>
> >>> dir(dummy)
> ['__doc__', '__module__', 'stuff', 'task']
>
> How do I find out, when working with a new class I'm not familiar
> with, how many attributes it has, and how many methods? dir() is a bit
> too generic because both look identical in the list...
>

What exactly do you want to know? If you want to know which are data
attributes and which are callables you can use the builtin callable
function.

>>> print callable.__doc__
callable(object) -> Boolean

Return whether the object is callable (i.e., some kind of function).
Note that classes are callable, as are instances with a __call__() method.
>>>

For other type of info, there are various answers. The most basic one starts
by reading the docstring of dir:

>>> print dir.__doc__
dir([object]) -> list of strings

Return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it:

[rest snipped]

Since it returns a list of strings you can just iterate over it. What
questions do you want to ask? A simple list comprehension can give you a
list of special names that dummy recognizes

[attrib for attrib in dir(dummy) if attrib.startswith('__') and
attrib.endswith('__')]

How many attributes?

len(dir(dummy))

Callable attributes?

[attrib for attrib in dir(dummy) if callable(getattr(dummy, attrib))]

etc.

> Alan
>

HTH, with my best regards,
G. Rodrigues