Source From Here
Question
I've seen plenty of examples of people extracting all of the classes from a module, usually something like:
But I can't find out how to get all of the classes from the current module.
How-To
Try this:
For example:
- common/Test.py
Then you can list the class in
common/Test.py this way:
Question
I've seen plenty of examples of people extracting all of the classes from a module, usually something like:
- # foo.py
- class Foo:
- pass
- # test.py
- import inspect
- import foo
- for name, obj in inspect.getmembers(foo):
- if inspect.isclass(obj):
- print obj
- # foo.py
- import inspect
- class Foo:
- pass
- def print_classes():
- for name, obj in inspect.getmembers(???): # what do I do here?
- if inspect.isclass(obj):
- print obj
- # test.py
- import foo
- foo.print_classes()
Try this:
- import sys
- current_module = sys.modules[__name__]
- common/Test.py
- class A:
- def __init__(self, name):
- self.name = name
- def __repr__(self):
- return "A-{}".format(self.name)
- class B:
- def __init__(self, name):
- self.name = name
- def __repr__(self):
- return "B-{}".format(self.name)
沒有留言:
張貼留言