模块

2018-03-19  本文已影响0人  钟速

创建文件hello.py,写入:

def hi():
   print('hello everyone!')

调用模块:

导入模块
  1. import 模块名
import hello
hello.hi()
  1. from 模块名 import 函数名
from hello import hi
hi()
  1. import 模块名 as 新名字
import hello as ho
ho.hi()
__name__ = '__main__'

在作为程序运行时,__name__属性的值为'__main__';在作为模块导入时,值为模块名。

# tem.py
def c2f(cel):
    fah = cel * 1.8 + 32
    return fah

def test():
    print('测试,0摄氏度 = %.2f 华氏度' % c2f(0))

if __name__ =='__main__':
    test

上面代码只有在单独运行tem.py时,才会执行test(),调用模块时不执行。


  1. 创建一个文件夹存放相关模块,文件夹名即包名。
  2. 在文件夹中创建一个__init__.py的模块文件,内容可以为空。
  3. 将相关模块放入文件中。
# tem.py
# 将tem.py放在文件M1中
import M1.tem as tc
上一篇下一篇

猜你喜欢

热点阅读