模块
模块的概念
模块的导入
import
import hm_099_测试模块1
import hm_100_测试模块2
hm_099_测试模块1.say_hello()
hm_100_测试模块2.say_hello()
dog = hm_099_测试模块1.Dog()
print(dog)
cat = hm_100_测试模块2.Cat()
print(cat)
import hm_099_测试模块1 as DogModule
import hm_100_测试模块2 as CatModule
DogModule.say_hello()
CatModule.say_hello()
dog = DogModule.Dog()
print(dog)
cat = CatModule.Cat()
print(cat)
from……import……
from hm_099_测试模块1 import Dog
from hm_100_测试模块2 import say_hello
say_hello()
wangcai = Dog()
print(wangcai)
导入所有工具
from hm_099_测试模块1 import *
from hm_100_测试模块2 import *
print(title)
say_hello()
wangcai = Dog()
print(wangcai)
from hm_099_测试模块1 import say_hello as module2_say_hello
from hm_100_测试模块2 import say_hello
say_hello()
module2_say_hello()
模块的搜索顺序
import random
print(random.__file__)
rand = random.randint(0, 10)
print(rand)
模块原则-每一个文件都应该是可以被导入的
name
# 全局变量/函数/类/,注意:直接执行的代码不是向外界提供的工具
def say_hello():
print("你好,我是say_hello")
#如果直接执行模块,__main__
if __name__ == "__main__":
print(__name__)
# 文件被导入时,能够直接执行的代码不需要被执行
print("小明开发的模块")
say_hello()
import hm_107_name模块
print("-" * 50)
包
包的案例
init.py
from . import send_message
from . import receive_message
receive_message.py
def receive():
return "这是来自 110 的短信"
send_message.py
def send(text):
print("正在发送 %s ..." % text)
导入包
import hm_message
hm_message.send_message.send("hello")
txt = hm_message.receive_message.receive()
print(txt)
发布模块
制作要发布的压缩包
创建setup.py
构建模块
生成发布压缩包
安装模块
pip安装第三方模块