简体   繁体   English

有没有办法在一个别名下导入多个模块?

[英]Is there a way to import multiple modules under one alias?

I'm trying to import multiple library files under a single alias, without the use of the init .py file (because it's apparently not supported by ROS). 我正在尝试在单个别名下导入多个库文件,而不使用init .py文件(因为它显然不受ROS支持)。

Example: 例:

Let's say we have the following files: 假设我们有以下文件:

foo/
   __init__.py # This file is empty, used to categorize foo as a package.
   a.py
   b.py
   c.py
bar/
   example.py

a, b and c all include different functions which I need in example, so I import them a,b和c都包含我在示例中需要的不同功能,因此我导入它们

#example.py

from foo import a, b, c

a.fn1()
b.fn2()
c.fn3()

This works, but is there some way I could group them all under a single alias? 这有效,但有一些方法我可以将它们全部归入一个别名吗? Like so: 像这样:

#example.py

from foo import [a, b, c] as foo

foo.fn1()
foo.fn2()
foo.fn3()

Again, I know this can be done by importing them under the init .py, but since our library is meant to work under ROS, we are currently unable to do as such without ending up with import errors when running in it ROS. 同样,我知道这可以通过在init .py下导入它们来完成,但由于我们的库本来是在ROS下工作,我们目前无法这样做而不会在运行ROS时遇到导入错误。

Thanks in advance. 提前致谢。

No. 没有。

One symbol in a script cannot refer to multiple modules at the same time. 脚本中的一个符号不能同时引用多个模块。

And using different names for different modules is a much cleaner approach anyway. 无论如何,为不同的模块使用不同的名称是一种更清洁的方法。 You can try to make your life a bit easier by using the wildcard import 您可以尝试使用通配符导入使您的生活更轻松

from foo.a import *
from foo.b import *
from foo.c import *

fn1()
fn2()
fn3()

But this ends up polluting your namespace. 但这最终会污染您的命名空间。 I wouldn't recommend it. 我不推荐它。

You could also try it ( * not recommended): 你也可以试试( *不推荐):

from foo.a import fn1
from foo.b import fn2
from foo.c import fn3

fn1()
fn2()
fn3()

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

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