How to find the classname of an object? (was Python Documentation)
Heiko Wundram
modelnine at ceosg.de
Fri May 13 02:32:22 EDT 2005
On Friday 13 May 2005 01:21, Christopher J. Bottaro wrote:
> For those of you following the Python Documentation thread, this is a good
> example of how the PHP manual is "better". I found how to do this in a few
> seconds in PHP. I searched the Python docs for "class name", "classname",
> "introspection" and "getclass". I looked in the Class section of the
> tutorial also and also the Programming FAQ. The "related functions"
> section of the PHP manual is really helpful. It would be cool if in the
> section for the built-in function isinstance() or issubclass() there is a
> section for "related functions" that would point me to getclassname(obj)
> (if it exists).
There is no function to do this in Python (so you'll have a hard time finding
it in the docs :-)), but there is a __bases__ member in any class/type which
lists the immediate bases (and this is documented in the language reference,
along with a reference in the tutorial when OO is introduced). Now, the
following method lists all base classes:
def getBases(cls):
bases = []
stack = [cls]
new_stack = []
while stack:
for cls in stack:
if cls not in bases:
bases.append(cls)
new_stack.extend(cls.__bases__)
stack = new_stack
new_stack = []
return bases
Example:
>>> class x(object):
... pass
...
>>> class y(x):
... pass
...
>>> class z(object):
... pass
...
>>> class a(z,y):
... pass
...
>>> def getBases(cls):
... bases = []
... stack = [cls]
... new_stack = []
... while stack:
... for cls in stack:
... if cls not in bases:
... bases.append(cls)
... new_stack.extend(cls.__bases__)
... stack = new_stack
... new_stack = []
... return bases
...
>>> getBases(a)
[<class '__main__.a'>, <class '__main__.z'>, <class '__main__.y'>, <type
'object'>, <class '__main__.x'>]
HTH!
--- Heiko.
More information about the Python-list
mailing list