我见过很多例子,人们从一个模块中提取所有的类,通常是这样的。
# 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()
这可能是非常明显的事情,但我没能找到任何东西。谁能帮帮我?
试试这个。
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()
需要一个谓词。
我可以从内置的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']
)
))
如果你想拥有所有属于当前模块的类,你可以使用这个.NET Framework 2.0。
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__]
这在我的经验中是比较有用的。