2018年4月19日 星期四

[ Python 常見問題 ] How can I get a list of all classes within current module in Python?

Source From Here 
Question 
I've seen plenty of examples of people extracting all of the classes from a module, usually something like: 
  1. # foo.py  
  2. class Foo:  
  3.     pass  
  4.   
  5. # test.py  
  6. import inspect  
  7. import foo  
  8.   
  9. for name, obj in inspect.getmembers(foo):  
  10.     if inspect.isclass(obj):  
  11.         print obj  
But I can't find out how to get all of the classes from the current module. 
  1. # foo.py  
  2. import inspect  
  3.   
  4. class Foo:  
  5.     pass  
  6.   
  7. def print_classes():  
  8.     for name, obj in inspect.getmembers(???): # what do I do here?  
  9.         if inspect.isclass(obj):  
  10.             print obj  
  11.   
  12. # test.py  
  13. import foo  
  14.   
  15. foo.print_classes()  
How-To 
Try this: 
  1. import sys  
  2. current_module = sys.modules[__name__]  
For example: 
- common/Test.py 
  1. class A:  
  2.     def __init__(self, name):  
  3.         self.name = name  
  4.   
  5.     def __repr__(self):  
  6.         return "A-{}".format(self.name)  
  7.   
  8.   
  9. class B:  
  10.     def __init__(self, name):  
  11.         self.name = name  
  12.   
  13.     def __repr__(self):  
  14.         return "B-{}".format(self.name)  
Then you can list the class in common/Test.py this way: 
>>> import sys, inspect 
>>> from common import Test 
>>> for name, clz in inspect.getmembers(sys.modules['common.Test'], inspect.isclass): 
... print('{}\t{}'.format(name, clz('Hello'))) // Print the name of class and initialize it 
... 
A A-Hello 
B B-Hello


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...