有没有办法在一个别名下导入多个模块? [英] Is there a way to import multiple modules under one alias?

查看:39
本文介绍了有没有办法在一个别名下导入多个模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在一个别名下导入多个库文件,而不使用 init.py 文件(因为它显然不受 ROS 支持).

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).

示例:

假设我们有以下文件:

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 和 c 都包含我在示例中需要的不同函数,因此我将它们导入

a, b and c all include different functions which I need in example, so I import them

#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()

同样,我知道这可以通过在 init.py 下导入它们来完成,但是由于我们的库旨在在 ROS 下工作,我们目前无法这样做而不会结束在ROS中运行时导入错误.

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.

提前致谢.

推荐答案

没有

脚本中的一个符号不能同时引用多个模块.

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.

这篇关于有没有办法在一个别名下导入多个模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆