如何在Python中获取当前模块中所有类的列表?

时间:2009-11-25 10:59:46

标签: python reflection inspect

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

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

这可能是非常明显的事情,但我找不到任何东西。任何人都可以帮助我吗?

12 个答案:

答案 0 :(得分:337)

试试这个:

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()采用谓词。

答案 1 :(得分:18)

怎么样?
g = globals().copy()
for name, obj in g.iteritems():

答案 2 :(得分:13)

我不知道是否有“正确”的方法,但您的代码段是正确的:只需将import foo添加到foo.py,执行inspect.getmembers(foo),它应该工作得很好。

答案 3 :(得分: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']
        )
    ))

答案 4 :(得分:6)

import pyclbr
print(pyclbr.readmodule(__name__).keys())

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

答案 5 :(得分:4)

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

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上使用的谓词的原因。该语句检查该类是否真正属于该模块。

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

答案 6 :(得分:3)

另一种适用于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()

答案 7 :(得分:2)

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

private static ushort WM_KEYDOWN = 0x0100;

这为您提供了一个类名列表。如果您想要类对象本身,只需保留obj即可。

import sys
import inspect

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

根据我的经验,这很有用。

答案 8 :(得分:0)

我认为您可以做这样的事情。

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

如果您需要自己的课程

答案 9 :(得分:0)

我经常发现自己在编写命令行实用程序,其中第一个参数旨在引用许多不同类中的一个。例如./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' : <Feature object> }。相同的kwargsfoo = 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

答案 10 :(得分:0)

import Foo 
dir(Foo)

import collections
dir(collections)

答案 11 :(得分:0)

转到Python解释器。键入 help('module_name'),然后按Enter。 例如 help('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
相关问题