Object and Class Exploration
Alex Martelli
aleaxit at yahoo.com
Fri May 4 06:04:07 EDT 2001
"Jason Joy" <kyroraz at usa.net> wrote in message
news:mailman.988938787.13378.python-list at python.org...
"""
If I have an object (or a instance of a class) ...
A = CLASS(FOO)
is there a way to do a loop such that I can see all the properties (or
everything def'd) within A?
"""
Within A, or within its class, or...?
"""
Example:
def Class(bar):
"""
You mean Class is a *function* that takes argument bar?
Or is it a *class* inheriting from class bar, in which
case you would write
class Class(bar):
...?
"""
def a:
## Stuff here
def b:
## Stuff Here
Result:
['a, b']
"""
If Class is indeed a function it IS a hard problem to
find out all the 'def' statement it will use to define
local functions in a given run -- it may depend on
the arguments, and a general solution may be as hard
as solving the halting problem, I think.
If Class is a class instead, then dir(Class) will
contain all of its methods's names as well as other
things such as '__doc__' for its docstring &c. You
may filter dir(Class) to eliminate all names with a
leading underscore, which are private or magical:
[x for x in dir(Class) if not x.startswith('_')]
or, of course
def normal_name(x):
return not x.startswith('_')
filter(normal_name, dir(Class))
If you have an object O that is an instance of
Class, O.__class__ will be a reference to the
Class object.
Note that this does *NOT* account for inherited
attributes and methods...! It takes a bit more
effort if you also want those.
Alex
More information about the Python-list
mailing list