在as后面添加逗号的导入

3 投票
1 回答
807 浏览
提问于 2025-04-18 12:18

我在查看一个代码库的时候,发现了一行有点奇怪的代码

from flask.ext.testing import TestCase as Base, Twill

像这样导入是什么意思呢?我之前没见过这种写法,而且在网上搜索也挺难找到相关信息。

1 个回答

6

这一行代码告诉Python要从flask.ext.testing这个包里导入TestCaseTwill,但是把TestCase导入时用Base这个名字。

根据文档的说明:

如果模块名后面跟着as,那么as后面的名字就直接和导入的模块绑定在一起。

下面是一个示例,展示了如何使用re模块中的searchmatch函数:

>>> from re import search as other, match
>>> match  # The name match refers to re.match
<function match at 0x02039780>
>>> other  # The name other refers to re.search
<function search at 0x02048A98>
>>> search  # The name search is not defined because it was imported as other
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'search' is not defined
>>>

撰写回答