列出目录中的类 (Python)
我正在开发一个 Python 2.6 包,在其中我想获取某个目录(包内)中所有类的列表,以便对类对象执行内省。
具体来说,如果包含当前正在执行的模块的目录有一个名为“foobar”的子目录,并且“foobar”包含指定 class Foo(MyBase)
、class Bar(MyBase)< 的 .py 文件/code> 和
,但不是 class Bar2
,我想获取继承自 MyBase
的类对象的引用列表,即 Foo
和 < code>BarBar2
。
我不确定这个任务是否真的需要涉及文件系统的任何处理,或者子目录中的模块是否自动加载并且只需要通过某种方式内省列出。请问这里有什么想法吗?非常感谢示例代码,因为我对 Python 还很陌生,尤其是内省。
I'm developing a Python 2.6 package in which I would like to fetch a list of all classes in a certain directory (within the package) in order to then perform introspection on the class objects.
Specifically, if the directory containing the currently executing module has a sub-dir called 'foobar' and 'foobar' contains .py files specifying class Foo(MyBase)
, class Bar(MyBase)
, and class Bar2
, I want to obtain a list of references to the class objects that inherit from MyBase
, i.e. Foo
and Bar
, but not Bar2
.
I'm not sure if this task actually need involve any dealing with the filesystem or if the modules in the sub-dir are automatically loaded and just need to be listed via introspection somehow. Any ideas here please? Example code is much appreciated, since I'm pretty new to Python, in particular introspection.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
模块永远不会自动加载,但应该很容易迭代目录中的模块并使用
__import__
内置函数加载它们:Modules are never loaded automatically, but it should be easy to iterate over the modules in the directory and load them with the
__import__
builtin function:我想做同样的事情,这就是我最终的结果:
希望它有帮助..
I wanted to do the same thing, this is what I ended up with:
Hope it helps..
选项 1:使用 -r 参数 grep for "^class (\a\w+)\(Myclass" 正则表达式。
选项 2:将目录作为包(创建一个空的 __init__.py 文件),导入它并递归地迭代其成员:
Option 1: grep for "^class (\a\w+)\(Myclass" regexp with -r parameter.
Option 2: make the directory a package (create an empty __init__.py file), import it and iterate recursively over its members:
我自己处理过,这是我的版本(分叉@krakover片段):
用法:
plugins
包含BasePlugin
类的实现Dealt with it myself, this is my version (forked @krakover snippet):
Usage:
plugins
contains implementations of aBasePlugin
class在具有egrep的平台上:
对于
get_classes('.')
,egrep返回类似以下内容:它被转换为路径、类名和直接祖先的元组:
如果您只想要路径,那就是< code>[item[0] for get_classes('.')]。
On platforms that have egrep:
For
get_classes('.')
, egrep returns something like:which is converted into tuples of the path, class name and direct ancestors:
If you just want the paths, that's
[item[0] for item in get_classes('.')]
.