[Edu-sig] Introspective Python

Kirby Urner urnerk@qwest.net
Sun, 26 Aug 2001 23:16:53 -0400


Here's some Python demonstrating introspection:  the function ls takes
and object and spits out the keys from its class dictionary, containing
a list of methods for that object.

Below:  list and string objects spill their guts:

>>> def ls(obj):
...    return getattr(obj.__class__,'__dict__').keys()
...
>>> ls([])
['sort', '__ne__', '__getattr__', '__getslice__', '__delitem__', '__mul__', 
'__str__', '__getitem__', 'pop', '__class__', '__setitem__', '__iadd__', 
'__add__',
'__gt__', '__rmul__', '__lt__', '__ge__', '__eq__', 'append', '__imul__', 
'extend', 'insert', '__setattr__', 'reverse', '__contains__', 'index', 
'__setslice__', 'count', 'remove', '__delattr__', '__le__', '__init__', 
'__hash__', '__new__',
'__len__', '__repr__']
>>> ls('s')
['upper', '__getslice__', '__ne__', 'lstrip', '__str__', 'replace', 
'isdigit', 'endswith', 'splitlines', 'rfind', 'strip', '__rmul__', '__lt__', 
'ljust', 'find', '__init__', 'index', '__setattr__', '__new__', 'isalnum', 
'__contains__', 'rindex', '__eq__', '__class__', '__getattr__', 'decode', 
'isalpha', 'split', 'rstrip', 'encode', 'translate', 'istitle', '__len__', 
'__mul__', 'startswith', '__getitem__', 'rjust', 'swapcase', 'islower', 
'__add__', '__gt__', 'capitalize', 'count', 'lower', 'join', 'center', 
'title', 'expandtabs', 'isspace', '__delattr__', '__le__', '__repr__', 
'__hash__', 'isupper', '__ge__']

Kirby