如何在Python中从var_str导入var_str
让我解释一下..
我想这样做:
a = "somedir.somefile"
b = "someclass"
from a import b
嗯,我想这样做来自动导入目录中的所有类,但我不知道有多少个类。
Let me explain..
I want to do this:
a = "somedir.somefile"
b = "someclass"
from a import b
Well, I want to do this to import automatic all classes inside a directory, and I don't know how many classes are there.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
现在你可以这样做:
now you can do this:
您需要
__import__
内置函数。不过,使用起来有点麻烦,因为它返回顶级模块,而不是路径的叶子。像这样的东西应该有效:You need the
__import__
built-in function. It's a bit fiddly to use, though, because it returns the top-level module, rather than the leaf of the path. Something like this should work:我认为你真正想做的是使用 __init__.py 和 __all__ 。有关详细信息,请参阅模块教程。
或者,还有
exec
。它会满足您的要求,但可能不是实现目标的最佳方式。I think what you actually want to do is use
__init__.py
and__all__
. Take a look at the modules tutorial for details.Alternatively, there's
exec
. It will do what you're asking, but is probably not the best way to get there.