本文介绍了Python:仅获取在带有dir()的导入模块中定义的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用Python编写的模块.现在,我想将其导入另一个脚本并列出我在此模块中定义的所有类.所以我尝试:

I've got a module written in Python. I now want to import it into another script and list all classes I defined in this module. So I try:

>>> import my_module
>>> dir(my_module)
['BooleanField', 'CharField', 'DateTimeField', 'DecimalField', 'MyClass', 'MySecondClass', 'ForeignKeyField', 'HStoreField', 'IntegerField', 'JSONField', 'TextField', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'datetime', 'db', 'division', 'os', 'struct', 'uuid']

我在my_module中定义的仅有两个类是MyClassMySecondClass,其他的东西都是我导入到my_module中的所有东西.

The only two classes which I defined in my_module are MyClass and MySecondClass, the other stuff are all things that I imported into my_module.

我现在希望能够以某种方式获取在my_module中定义的所有类的列表,而无需获取所有其他内容.有没有办法在Python中做到这一点?

I now want to somehow be able to get a list of all classes which are defined in my_module without getting all the other stuff. Is there a way to do this in Python?

推荐答案

使用inspect模块检查活动对象:

Use the inspect module to inspect live objects:

>>> import inspect
>>> import my_module
>>> [m[0] for m in inspect.getmembers(my_module, inspect.isclass) if m[1].__module__ == 'my_module']

这应该可以工作,并在该my_module中定义每个class.

That should then work, getting every class defined within that my_module.

这篇关于Python:仅获取在带有dir()的导入模块中定义的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 17:29