創(chuàng)建文件hello.py水由,寫入:
def hi():
print('hello everyone!')
調(diào)用模塊:
導(dǎo)入模塊
- import 模塊名
import hello
hello.hi()
- from 模塊名 import 函數(shù)名
from hello import hi
hi()
- import 模塊名 as 新名字
import hello as ho
ho.hi()
__name__ = '__main__'
在作為程序運(yùn)行時(shí)晴叨,__name__屬性的值為'__main__'驰凛;在作為模塊導(dǎo)入時(shí)绍昂,值為模塊名鳖悠。
# tem.py
def c2f(cel):
fah = cel * 1.8 + 32
return fah
def test():
print('測試拓瞪,0攝氏度 = %.2f 華氏度' % c2f(0))
if __name__ =='__main__':
test
上面代碼只有在單獨(dú)運(yùn)行tem.py時(shí),才會(huì)執(zhí)行test()只厘,調(diào)用模塊時(shí)不執(zhí)行烙丛。
包
- 創(chuàng)建一個(gè)文件夾存放相關(guān)模塊,文件夾名即包名懈凹。
- 在文件夾中創(chuàng)建一個(gè)__init__.py的模塊文件蜀变,內(nèi)容可以為空。
- 將相關(guān)模塊放入文件中介评。
# tem.py
# 將tem.py放在文件M1中
import M1.tem as tc