简体   繁体   English

如何获取从 Python 3 中的模块导入的所有类的列表?

[英]How can I get a list of all classes I import from a module in Python 3?

I want to create a list consisting of the names of all classes I import from a certain folder.我想创建一个列表,其中包含我从某个文件夹导入的所有类的名称。

At the moment I have something like this:目前我有这样的事情:

from .my_classes import Class1, Class2, Class3
list_of_classes = [Class1.__name__, Class2.__name__, Class3.__name__]

But I want to convert it to something less manual:但我想将其转换为更少手动的东西:

from .my_classes import *

# .my_classes is obviously not working
list_of_classes = [cls.__name__ for cls in .my_classes]

How can I get .my_classes as a list?如何获取.my_classes作为列表?

.my_classes is a folder with this structure: .my_classes是具有以下结构的文件夹:

my_classes
|
|--__init__.py
|--some_classes_here.py
|--some_more_classes_here.py

Basically the imported objects become attributes of your module.基本上,导入的对象成为模块的属性。 So calling vars() will put all the parameters.因此调用vars()将放置所有参数。

If you put it after your import you should see it.如果你把它放在你的导入之后,你应该会看到它。

Please note that if you import import x as y you will see y and not x请注意,如果您将import x as y您将看到y而不是x

example:例子:

import collections
import re
print([x for x in vars() if  not (x.startswith('__') and x.endswith('__'))])
['collections', 're']

You can use locals() to collect the names in your current namespace and then inspect which module they came from using the __module__ attribute.您可以使用locals()收集当前命名空间中的名称,然后使用__module__属性检查它们来自哪个模块。 This only works for classes and functions.这仅适用于类和函数。

from .my_classes import *

classes = []
for name, item in locals().copy().items():
    try:
        if item.__module__ == 'my_classes':
            classes.append(item.__name__)
    except AttributeError:
        continue

classes
# returns:
['Class1', 'Class2', 'Class3']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM