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

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

这是可能的东西真的很明显,但我一直没能找到任何东西。谁能帮助我吗?

有帮助吗?

解决方案

尝试这种情况:

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()需要谓词。

其他提示

什么

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

我不知道是否有一个“正确”的方式来做到这一点,但你的片段是在正确的轨道上:只需添加import foo到foo.py,做inspect.getmembers(foo),它应该正常工作

我能得到从 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']
        )
    ))
import pyclbr
print(pyclbr.readmodule(__name__).keys())

注意,STDLIB的Python类浏览器模块使用静态源分析,所以它仅适用于由一个真实的.py文件备份模块。

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

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使用的谓词。这个语句检查,类真正属于该模块。

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

另一种解决方案,其在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()

这是我使用来获取所有已在当前模块中被定义的类的线(即,不导入)。它的长一点,根据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__]

这是已经在我的经验更有用。

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

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

如果你需要自己的类

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top