您的位置:首页 > 编程语言 > Python开发

【python】if __name__ == "__main__"

2017-02-16 10:14 417 查看
part1:

TemperatureConversion.py

def c2f(cel):
fal = cel * 1.8 + 32
return fal

def f2c(fah):
cel = (fah - 32) / 1.8
return cel

def test():
print("main函数")
print("0摄氏度 = %.2f华氏度" % c2f(0))
print("0华氏度 = %.2f摄氏度" % f2c(0))

test()


calc.py

import TemperatureConversion as tc

print("模块")
print("32摄氏度 = %.2f华氏度" % tc.c2f(32))
print("99华氏度 = %.2f摄氏度" % tc.f2c(99))


result:



improvement:if __name__ == "__main__"
part2:

TemperatureConversion.py

def c2f(cel):
fal = cel * 1.8 + 32
return fal

def f2c(fah):
cel = (fah - 32) / 1.8
return cel

def test():
print("main函数")
print("0摄氏度 = %.2f华氏度" % c2f(0))
print("0华氏度 = %.2f摄氏度" % f2c(0))

if __name__ == "__main__":
test()


calc.py

import TemperatureConversion as tc

print("模块")
print("32摄氏度 = %.2f华氏度" % tc.c2f(32))
print("99华氏度 = %.2f摄氏度" % tc.f2c(99))


result:



analysis:

1、cal.py,__name__ == "__main__"
2、TemperatureConversion.py,tc.__name__=="__TemperatureConversion__"
3、对应__name__的值选择是否执行(if __name__ == "__main__")


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: