candf.py
def c2f(cel):
fah = cel * 1.8 + 32
return fah
def f2c(fah):
cel = (fah - 32) / 1.8
return cel
def test():
print("测试数据:0 摄氏度 = %.2f 华氏度" % c2f(0))
print("测试数据:0 华氏度 = %.2f 摄氏度" % f2c(0))
test()
demo.py
import candf
print("32 摄氏度 = %.2f 华氏度" % candf.c2f(32))
print("99 华氏度 = %.2f 摄氏度" % candf.f2c(99))
运行demo.py,结果为
测试数据:0 摄氏度 = 32.00 华氏度
测试数据:0 华氏度 = -17.78 摄氏度
32 摄氏度 = 89.60 华氏度
99 华氏度 = 37.22 摄氏度
python解释器将模块(candf.py)中的测试代码也一块儿运行了,这并不是我们想要的结果。想要避免这种情况的关键在于,要让 Python 解释器知道,当前要运行的程度代码,是模块文件本身,还是导入模块的其它程序。
为了实现这一点,就需要使用 Python 内置的系统变量 name,它用于标识所在模块的模块名。
解决办法:
candf.py
def c2f(cel):
fah = cel * 1.8 + 32
return fah
def f2c(fah):
cel = (fah - 32) / 1.8
return cel
def test():
print("测试数据:0 摄氏度 = %.2f 华氏度" % c2f(0))
print("测试数据:0 华氏度 = %.2f 摄氏度" % f2c(0))
if __name__ == '__main__':
test()
这个时候再运行demo.py就不会在打印candf.py输出了
32 摄氏度 = 89.60 华氏度
99 华氏度 = 37.22 摄氏度
总结: 我们在命令行运行demo.py模块文件时,Python解释器把一个特殊变量__name__
置为__main__
,而如果在其他地方导入该demo.py 模块时,if
判断将失败,即为不会执行到test()方法。