问题:如何获取Python当前模块中所有类的列表?
我见过很多人从一个模块中提取所有类的示例,通常是这样的:
# 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()
这可能确实很明显,但是我什么也找不到。谁能帮我吗?
I’ve seen plenty of examples of people extracting all of the classes from a module, usually something like:
# foo.py
class Foo:
pass
# test.py
import inspect
import foo
for name, obj in inspect.getmembers(foo):
if inspect.isclass(obj):
print obj
Awesome.
But I can’t find out how to get all of the classes from the current module.
# 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()
This is probably something really obvious, but I haven’t been able to find anything. Can anyone help me out?
回答 0
尝试这个:
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()
带谓语。
Try this:
import sys
current_module = sys.modules[__name__]
In your context:
import sys, inspect
def print_classes():
for name, obj in inspect.getmembers(sys.modules[__name__]):
if inspect.isclass(obj):
print(obj)
And even better:
clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass)
Because inspect.getmembers()
takes a predicate.
回答 1
关于什么
g = globals().copy()
for name, obj in g.iteritems():
?
What about
g = globals().copy()
for name, obj in g.iteritems():
?
回答 2
我不知道是否有“适当的”方法来执行此操作,但是您的代码片段import foo
处在正确的轨道上:只需将其添加到foo.py中,do inspect.getmembers(foo)
,它就可以正常工作。
I don’t know if there’s a ‘proper’ way to do it, but your snippet is on the right track: just add import foo
to foo.py, do inspect.getmembers(foo)
, and it should work fine.
回答 3
我能够从dir
内置plus中获得所需的一切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']
)
))
I was able to get all I needed from the dir
built in plus 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)
Though, it does come out looking like a hairball:
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
import pyclbr
print(pyclbr.readmodule(__name__).keys())
请注意,stdlib的Python类浏览器模块使用静态源分析,因此它仅适用于由实际.py
文件支持的模块。
import pyclbr
print(pyclbr.readmodule(__name__).keys())
Note that the stdlib’s Python class browser module uses static source analysis, so it only works for modules that are backed by a real .py
file.
回答 5
如果要拥有属于当前模块的所有类,则可以使用以下方法:
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
。该语句检查该类是否确实属于该模块。
谓词是一个函数(可调用),它返回布尔值。
If you want to have all the classes, that belong to the current module, you could use this :
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)
If you use Nadia’s answer and you were importing other classes on your module, that classes will be being imported too.
So that’s why member.__module__ == __name__
is being added to the predicate used on is_class_member
. This statement checks that the class really belongs to the module.
A predicate is a function (callable), that returns a boolean value.
回答 6
另一个可在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()
Another solution which works in Python 2 and 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
这是我用来获取当前模块中已定义(即未导入)的所有类的行。根据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__]
根据我的经验,这是更有用的。
This is the line that I use to get all of the classes that have been defined in the current module (ie not imported). It’s a little long according to PEP-8 but you can change it as you see fit.
import sys
import inspect
classes = [name for name, obj in inspect.getmembers(sys.modules[__name__], inspect.isclass)
if obj.__module__ is __name__]
This gives you a list of the class names. If you want the class objects themselves just keep obj instead.
classes = [obj for name, obj in inspect.getmembers(sys.modules[__name__], inspect.isclass)
if obj.__module__ is __name__]
This is has been more useful in my experience.
回答 8
import Foo
dir(Foo)
import collections
dir(collections)
import Foo
dir(Foo)
import collections
dir(collections)
回答 9
我认为您可以做这样的事情。
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())`
如果您需要自己的类
I think that you can do something like this.
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())`
if you need own classes
回答 10
我经常发现自己在编写命令行实用程序,其中第一个参数旨在引用许多不同类中的一个。例如./something.py feature command —-arguments
,where Feature
是一个类,并且command
是该类上的一个方法。这是一个使这变得容易的基类。
假设该基类与所有子类都位于一个目录中。然后ArgBaseClass(foo = bar).load_subclasses()
,您可以拨打电话,这将返回字典。例如,如果目录如下所示:
- arg_base_class.py
- feature.py
假设feature.py
工具class Feature(ArgBaseClass)
,则上述调用load_subclasses
将返回{ 'feature' : <Feature object> }
。相同的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
I frequently find myself writing command line utilities wherein the first argument is meant to refer to one of many different classes. For example ./something.py feature command —-arguments
, where Feature
is a class and command
is a method on that class. Here’s a base class that makes this easy.
The assumption is that this base class resides in a directory alongside all of its subclasses. You can then call ArgBaseClass(foo = bar).load_subclasses()
which will return a dictionary. For example, if the directory looks like this:
- arg_base_class.py
- feature.py
Assuming feature.py
implements class Feature(ArgBaseClass)
, then the above invocation of load_subclasses
will return { 'feature' : <Feature object> }
. The same kwargs
(foo = bar
) will be passed into the Feature
class.
#!/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
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。