Other classes in a module

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Mon Mar 26 07:10:02 EDT 2007


Daniel Nogradi a écrit :
>> Can an instance of a class in a module, in any simple way find out which
>> other classes that exists in said module ?
> 
> 
> ##### module x ##########
> class c1:
>    pass
> 
> class c2:
>    pass
> #######################
> 
> 
> Python 2.5 (r25:51908, Nov  1 2006, 11:42:37)
> [GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import types
>>>> import x
>>>> for i in dir(x):
> ...     if type(getattr(x,i)) is types.ClassType:
> ...             print "Hey, '%s' is a class!" % i
> ...
> Hey, 'c1' is a class!
> Hey, 'c2' is a class!
>>>>
> 
> 
> It might be not exactly what you want but maybe still helps.

Doesn't work with new-style classes:

 >>> class Foo(object): pass
...
 >>> import typs
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
ImportError: No module named typs
 >>> import types
 >>> type(Foo) is types.ClassType
False
 >>>



More information about the Python-list mailing list