Python:仅使用 dir() 获取在导入模块中定义的类? [英] Python: get only classes defined in imported module with dir()?
问题描述
我有一个用 Python 编写的模块.我现在想将它导入另一个脚本并列出我在这个模块中定义的所有类.所以我尝试:
<预><代码>>>>导入 my_module>>>目录(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 中定义的仅有的两个类是 MyClass
和 MySecondClass
,其他的都是我导入到 my_module
中的东西.
我现在希望能够以某种方式获得 my_module
中定义的所有类的列表,而无需获取所有其他内容.有没有办法在 Python 中做到这一点?
使用 inspect
模块检查活动对象:
然后应该可以工作,获取在该 my_module
中定义的每个 class
.
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']
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
.
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?
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']
That should then work, getting every class
defined within that my_module
.
这篇关于Python:仅使用 dir() 获取在导入模块中定义的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!