如何获取模块中定义但未导入的所有类?
我已经看到了以下问题,但它并没有完全满足我的要求: 如何获取 Python 中当前模块内所有类的列表?
特别是,我不希望导入类,例如,如果我有以下模块:
from my.namespace import MyBaseClass
from somewhere.else import SomeOtherClass
class NewClass(MyBaseClass):
pass
class AnotherClass(MyBaseClass):
pass
class YetAnotherClass(MyBaseClass):
pass
如果我使用 cls成员= spect.getmembers(sys.modules[__name__], inform.isclass)
就像链接问题中接受的答案所示,它将返回 MyBaseClass
和 SomeOtherClass
除了本模块中定义的 3 个之外。
如何只获取 NewClass
、AnotherClass
和 YetAnotherClass
?
I've already seen the following question but it doesn't quite get me where I want: How can I get a list of all classes within current module in Python?
In particular, I do not want classes that are imported, e.g. if I had the following module:
from my.namespace import MyBaseClass
from somewhere.else import SomeOtherClass
class NewClass(MyBaseClass):
pass
class AnotherClass(MyBaseClass):
pass
class YetAnotherClass(MyBaseClass):
pass
If I use clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass)
like the accepted answer in the linked question suggests, it would return MyBaseClass
and SomeOtherClass
in addition to the 3 defined in this module.
How can I get only NewClass
, AnotherClass
and YetAnotherClass
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
检查类的 __module__ 属性以找出它是在哪个模块中定义的。
Inspect the
__module__
attribute of the class to find out which module it was defined in.对于回答这样一个老问题,我深表歉意,但我对使用此解决方案的检查模块感到不舒服。我在某处读到在生产中使用不安全。
初始化 a 中的所有类模块转换为列表中的无名对象
请参阅Antonis Christofides 对答案 1 的评论。
我得到了测试对象是否是一个类的答案
如何检查变量是否是是否有类?
所以这是我的免检查解决方案
I apologize for answering such an old question, but I didn't feel comfortable using the inspect module for this solution. I read somewhere that is wasn't safe to use in production.
Initialize all the classes in a module into nameless objects in a list
See Antonis Christofides comment to answer 1.
I got the answer for testing if an object is a class from
How to check whether a variable is a class or not?
So this is my inspect-free solution
您可能还想考虑使用标准库中的“Python 类浏览器”模块:
http://docs.python.org/library/pyclbr.html
因为它没有它实际上执行有问题的模块(它执行朴素的源检查),有一些它不太正确理解的特定技术,但对于所有“正常”类定义,它会准确地描述它们。
You may also want to consider using the "Python class browser" module in the standard library:
http://docs.python.org/library/pyclbr.html
Since it doesn't actually execute the module in question (it does naive source inspection instead) there are some specific techniques it doesn't quite understand correctly, but for all "normal" class definitions, it will describe them accurately.
我使用了以下内容:
我不想在中键入当前模块名称
I used the below:
I didn't want to type the current module name in
保持简单的解决方案:
命令行帮助:
-c cmd:程序以字符串形式传入(终止选项列表)
如果 Python 尝试加载,如果未找到,则会给出以下错误类型:
The Keep it simple solution:
Command line help:
-c cmd : program passed in as string (terminates option list)
If Python will attempt to loading, if not found gives these error types: