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

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

这可能是非常明显的事情,但我还没有找到任何东西。有人能帮帮我吗?


当前回答

进入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

其他回答

是什么

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

?

我可以从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']
        )
    ))

进入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

试试这个:

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()接受一个谓词。

这是一行,我用来获得所有的类,已定义在当前模块(即未导入)。根据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__]

在我的经验中,这是更有用的。