为什么我不需要导入支持模块?



get_square_root()函数依赖于math模块。要调用analysis.py中的get_square_root()函数,我不需要导入math模块,为什么?


# calculator.py
import math
def get_square_root(a):
    return math.sqrt(a)
#analysis.py
import calculator
calculator.get_square_root(5)

我在python中对import有所了解(如果我理解错误,请纠正我(。当import calculator时,Python解释器读取整个calculator.py模块,但读取<ModuleName>.<ObjectName>不访问模块中的对象。这就是我在analysis.py中对get_square_root()的调用方式。但是由于analysis.py中没有mathget_square_root()是如何访问math的?

以任何方式运行calculator时,math都绑定在其模块范围内,使其可访问get_square_root

当您在analysis中运行import calculator时,math仍在get_square_root的模块范围内,加上calculator绑定在analysis的范围内,因此您可以将其作为calculator.math访问。

analysis中运行from calculator import get_square_root时,math仍在get_square_root的模块范围内,但由于calculator未绑定,因此无法从analysis访问它。

最新更新