inspect.getmembers(object[, typecheck])
First from the conclusion
foo.py
class foo1:
'''something code'''
class foo2:
'''something code'''
class foo3:
'''something code'''
get_class
import foo
import inspect
classes = map(lambda x:x[0],inspect.getmembers(foo,inspect.isclass))
print classes
# => ['foo1','foo2','foo3']
ʻInspect.getmembers (object) gets all the members of the object registered in ʻobject
.
The format is [(member1, type), (member2, type), ....].
ʻInspect.is--determines if the object matches
--`
It seems that there are 16 classes, modules, functions, method .....
For more information, click here (http://docs.python.jp/2/library/inspect.html "inspect").
Therefore, ʻinspect.getmembers (foo, inspect.isclass)` should have been like this.
get_class
print inspect.getmembers(foo,inspect.isclass)
# => [('foo1',<class foo.foo1 at 0x*******>),('foo1',<class foo.foo2 at 0x*******>),('foo3',<class foo.foo3 at 0x*******>)]
After that, you only have to extract the 0th element of each element.
map(lambda x:x[0], list)
That's it.
Since the first element is the class itself, you can also get the class object itself. For example, suppose you search key for a part of the class name and get a matching class object.
getclass
import foo
import inspect
classes = inspect.getmembers(foo,inspect.isclass)
for i in classes:
if '2' in i[0]:
something2 = i[1]
something2class = something2()
print something2class.__class__.__name__
# => foo2
However, in this case, if you do not find it, you will probably get an error.
Recommended Posts