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
中没有math
,get_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
访问它。