如何在Python中从var_str导入var_str

发布于 2024-12-02 20:15:52 字数 151 浏览 1 评论 0原文

让我解释一下..

我想这样做:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

清引 2024-12-09 20:15:52
a = "somedir.somefile"
b = "someclass"

module = __import__(a, globals(), locals(), [b], -1)
clazz = getattr(module, b)

现在你可以这样做:

instance = clazz()
instance.method()
a = "somedir.somefile"
b = "someclass"

module = __import__(a, globals(), locals(), [b], -1)
clazz = getattr(module, b)

now you can do this:

instance = clazz()
instance.method()
月下凄凉 2024-12-09 20:15:52

您需要 __import__ 内置函数。不过,使用起来有点麻烦,因为它返回顶级模块,而不是路径的叶子。像这样的东西应该有效:

from operator import attrgetter
module_path = 'a.b.c'
class_name = 'd'

module = __import__(module_path)
attribute_path = module_path.split('.') + [class_name]
# drop the top-level name
attribute_path = attribute_path[1:]
klass = attrgetter('.'.join(attribute_path))(module)

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:

from operator import attrgetter
module_path = 'a.b.c'
class_name = 'd'

module = __import__(module_path)
attribute_path = module_path.split('.') + [class_name]
# drop the top-level name
attribute_path = attribute_path[1:]
klass = attrgetter('.'.join(attribute_path))(module)
围归者 2024-12-09 20:15:52

我认为你真正想做的是使用 __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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文