在as后面添加逗号的导入
我在查看一个代码库的时候,发现了一行有点奇怪的代码
from flask.ext.testing import TestCase as Base, Twill
像这样导入是什么意思呢?我之前没见过这种写法,而且在网上搜索也挺难找到相关信息。
1 个回答
6
这一行代码告诉Python要从flask.ext.testing
这个包里导入TestCase
和Twill
,但是把TestCase
导入时用Base
这个名字。
根据文档的说明:
如果模块名后面跟着
as
,那么as
后面的名字就直接和导入的模块绑定在一起。
下面是一个示例,展示了如何使用re
模块中的search
和match
函数:
>>> 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
>>>