【问题标题】:How can I get a list of all classes within current module in Python?如何获取 Python 中当前模块中所有类的列表?
【发布时间】:2010-12-20 06:02:06
【问题描述】:

我见过很多人从一个模块中提取所有类的例子,通常是这样的:

# foo.py
class Foo:
    pass

# test.py
import inspect
import foo

for name, obj in inspect.getmembers(foo):
    if inspect.isclass(obj):
        print obj

太棒了。

但我不知道如何从 current 模块中获取所有类。

# 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()

这可能是非常明显的事情,但我无法找到任何东西。谁能帮帮我?

【问题讨论】:

  • 有一个PEP 表示这样的功能,但被拒绝了。
  • 阅读"class"的源代码有什么问题?为什么那行不通?
  • 我猜这个问题是关于想要自动化某些任务,所以以编程方式完成它很重要。大概提问者认为通过眼睛阅读源代码手动执行此操作可能是重复的、容易出错或耗时的。
  • 我根据这个问题为检查一个类而创建的一个简单的衬里是:[name for name,obj in inspect.getmembers(foo) if inspect.isclass(obj)]

标签: python reflection inspect


【解决方案1】:

转到 Python 解释器。输入 help ('module_name') ,然后按 Enter。 例如帮助('os') 。 在这里,我粘贴了以下输出的一部分:

class statvfs_result(__builtin__.object)
     |  statvfs_result: Result from statvfs or fstatvfs.
     |
     |  This object may be accessed either as a tuple of
     |    (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),
     |  or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.
     |
     |  See os.statvfs for more information.
     |
     |  Methods defined here:
     |
     |  __add__(...)
     |      x.__add__(y) <==> x+y
     |
     |  __contains__(...)
     |      x.__contains__(y) <==> y in x

【讨论】:

    【解决方案2】:
    import Foo 
    dir(Foo)
    
    import collections
    dir(collections)
    

    【讨论】:

    • dir() 也会包含导入的类,而且你无法确定它是导入的类还是定义的类
    【解决方案3】:

    我经常发现自己在编写命令行实用程序,其中第一个参数旨在引用许多不同类中的一个。例如./something.py feature command —-arguments,其中Feature 是一个类,command 是该类的一个方法。这是一个使这变得简单的基类。

    假设这个基类与它的所有子类一起位于一个目录中。然后您可以调用ArgBaseClass(foo = bar).load_subclasses(),它将返回一个字典。例如,如果目录如下所示:

    • arg_base_class.py
    • feature.py

    假设feature.py实现class Feature(ArgBaseClass),那么上面对load_subclasses的调用将返回{ 'feature' : &lt;Feature object&gt; }。相同的kwargs (foo = bar) 将被传递到Feature 类中。

    #!/usr/bin/env python3
    import os, pkgutil, importlib, inspect
    
    class ArgBaseClass():
        # Assign all keyword arguments as properties on self, and keep the kwargs for later.
        def __init__(self, **kwargs):
            self._kwargs = kwargs
            for (k, v) in kwargs.items():
                setattr(self, k, v)
            ms = inspect.getmembers(self, predicate=inspect.ismethod)
            self.methods = dict([(n, m) for (n, m) in ms if not n.startswith('_')])
    
        # Add the names of the methods to a parser object.
        def _parse_arguments(self, parser):
            parser.add_argument('method', choices=list(self.methods))
            return parser
    
        # Instantiate one of each of the subclasses of this class.
        def load_subclasses(self):
            module_dir = os.path.dirname(__file__)
            module_name = os.path.basename(os.path.normpath(module_dir))
            parent_class = self.__class__
            modules = {}
            # Load all the modules it the package:
            for (module_loader, name, ispkg) in pkgutil.iter_modules([module_dir]):
                modules[name] = importlib.import_module('.' + name, module_name)
    
            # Instantiate one of each class, passing the keyword arguments.
            ret = {}
            for cls in parent_class.__subclasses__():
                path = cls.__module__.split('.')
                ret[path[-1]] = cls(**self._kwargs)
            return ret
    

    【讨论】:

      【解决方案4】:

      这是我用来获取所有已在当前模块中定义的类(即未导入)的行。根据 PEP-8,它有点长,但您可以根据需要进行更改。

      import sys
      import inspect
      
      classes = [name for name, obj in inspect.getmembers(sys.modules[__name__], inspect.isclass) 
                if obj.__module__ is __name__]
      

      这会给你一个类名列表。如果您想要类对象本身,只需保留 obj 即可。

      classes = [obj for name, obj in inspect.getmembers(sys.modules[__name__], inspect.isclass)
                if obj.__module__ is __name__]
      

      这在我的经验中更有用。

      【讨论】:

        【解决方案5】:

        我认为你可以这样做。

        class custom(object):
            __custom__ = True
        class Alpha(custom):
            something = 3
        def GetClasses():
            return [x for x in globals() if hasattr(globals()[str(x)], '__custom__')]
        print(GetClasses())`
        

        如果你需要自己的课程

        【讨论】:

          【解决方案6】:

          如果你想拥有属于当前模块的所有类,你可以使用这个:

          import sys, inspect
          def print_classes():
              is_class_member = lambda member: inspect.isclass(member) and member.__module__ == __name__
              clsmembers = inspect.getmembers(sys.modules[__name__], is_class_member)
          

          如果您使用 Nadia 的答案并且您在模块上导入其他类,那么这些类也将被导入。

          这就是为什么将member.__module__ == __name__ 添加到is_class_member 上使用的谓词中的原因。该语句检查该类是否确实属于该模块。

          谓词是一个函数(可调用),它返回一个布尔值。

          【讨论】:

            【解决方案7】:

            另一个适用于 Python 2 和 3 的解决方案:

            #foo.py
            import sys
            
            class Foo(object):
                pass
            
            def print_classes():
                current_module = sys.modules[__name__]
                for key in dir(current_module):
                    if isinstance( getattr(current_module, key), type ):
                        print(key)
            
            # test.py
            import foo
            foo.print_classes()
            

            【讨论】:

            • 这在 3.6.8 中不起作用。我没有收到任何模块错误。
            【解决方案8】:

            我能够从内置的dir 加上getattr 获得我需要的一切。

            # Works on pretty much everything, but be mindful that 
            # you get lists of strings back
            
            print dir(myproject)
            print dir(myproject.mymodule)
            print dir(myproject.mymodule.myfile)
            print dir(myproject.mymodule.myfile.myclass)
            
            # But, the string names can be resolved with getattr, (as seen below)
            

            不过,它看起来确实像一个毛球:

            def list_supported_platforms():
                """
                    List supported platforms (to match sys.platform)
            
                    @Retirms:
                        list str: platform names
                """
                return list(itertools.chain(
                    *list(
                        # Get the class's constant
                        getattr(
                            # Get the module's first class, which we wrote
                            getattr(
                                # Get the module
                                getattr(platforms, item),
                                dir(
                                    getattr(platforms, item)
                                )[0]
                            ),
                            'SYS_PLATFORMS'
                        )
                        # For each include in platforms/__init__.py 
                        for item in dir(platforms)
                        # Ignore magic, ourselves (index.py) and a base class.
                        if not item.startswith('__') and item not in ['index', 'base']
                    )
                ))
            

            【讨论】:

              【解决方案9】:

              试试这个:

              import sys
              current_module = sys.modules[__name__]
              

              在您的上下文中:

              import sys, inspect
              def print_classes():
                  for name, obj in inspect.getmembers(sys.modules[__name__]):
                      if inspect.isclass(obj):
                          print(obj)
              

              甚至更好:

              clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass)
              

              因为inspect.getmembers() 接受谓词。

              【讨论】:

              • 如果我在模块级别(即from optparse import OptionParser)在此模块中导入类,则这些模块将包含在打印列表中。我该如何避免呢?
              • @phasetwenty,而不是 inspect.isclass 你可以有类似的东西:inspect.getmembers(sys.modules[__name__], lambda member: member.__module__ == __name__ and isnpect.isclass)
              • dict(inspect.getmembers(sys.modules[__name__])) == globals() 始终是True,那么为什么要导入?
              • Nadia 的回答几乎是正确的。更好:inspect.getmembers(sys.modules[__name__], lambda member: inspect.isclass(member) and member.__module__ == __name__
              • @JohnM。因为 Nadia 忘了打电话给isclass
              【解决方案10】:
              import pyclbr
              print(pyclbr.readmodule(__name__).keys())
              

              请注意,stdlib 的 Python 类浏览器模块使用静态源代码分析,因此它仅适用于由真正的 .py 文件支持的模块。

              【讨论】:

                【解决方案11】:

                怎么样

                g = globals().copy()
                for name, obj in g.iteritems():
                

                ?

                【讨论】:

                • 这是我通常做的。其他答案似乎更“干净”,但不知道。
                • 对我来说似乎很干净,特别是如果您过滤 isinstance(obj, types.ClassType)
                • 我更喜欢这个答案,因为即使当前模块没有放在 sys.modules 中,它也会起作用,例如来自docs.python.org/2/library/functions.html#execfile
                • @ChrisSmith 特别是,我今天发现一些调试器(例如pudb)以这种方式运行您的程序,这导致使用sys.modules 的代码在调试时随机中断。 globals() 看起来有点丑,但似乎可靠多了。
                【解决方案12】:

                我不知道是否有“正确”的方法可以做到这一点,但你的 sn-p 是在正确的轨道上:只需将 import foo 添加到 foo.py,执行 inspect.getmembers(foo),它应该可以正常工作.

                【讨论】:

                • 哇,我原以为这会产生循环依赖之类的,但它确实有效!
                • 你没有得到循环依赖或导入循环的原因是,一旦你导入一个模块,它就会被添加到全局命名空间中。当导入的模块被执行并进入“import foo”时,它会跳过导入,因为该模块已经在全局变量中可用。如果您将 foo 作为 main(作为脚本)执行,则该模块实际上会运行两次,因为当您进入 'import foo' 时,main 将位于全局命名空间中,但不在 foo 中。在“import foo”之后,“main”和“foo”都将位于全局命名空间中。
                猜你喜欢
                • 2010-10-08
                • 1970-01-01
                • 2011-09-21
                • 1970-01-01
                • 2010-09-24
                • 1970-01-01
                • 1970-01-01
                • 2020-02-16
                相关资源
                最近更新 更多