python基础入门之十八 —— 模块和包

时间:2020-04-07 00:16:38   收藏:0   阅读:72

一、模块

模块能定义函数,类和变量,模块里也能包含可执行代码。

1、 导入模块

# 法1:import 模块
import math
print(math.sqrt(9))
# 法2:from 模块 import 功能1,功能2,……
from math import sqrt
print(sqrt(8))
# 法3:from 模块 import *
from math import *
print(sqrt(8))

2、模块别名

# 别名1:
import time as t
t.sleep(1)
# 别名2:
from time import sleep as sl
sl(1)

3、制作模块

系统变量:

模块:module.py

__all__ = [println,test]

def println(a,b):
    print(a+b)

def test(a,b):
    print(a*b)

if __name__ == __main__:
 println(1,2)
 print(__name__)

调用文件:demo.py

from module import *

println(2,3)  # 5
test(1,2)  # 2

P.s:如果功能名字重复,调用到的是最后定义或导入的功能

 

二 、包

1、创建包

技术图片

 

 新建包后,包内部会自动创建__init__.py文件,这个文件控制着包的导入行为

 

2、导包

P.s:使用‘from 包 import *’这个导包一定要在__init__.py文件中定义__all__,否则报错

技术图片

 

 m1.py:

def info():
    print(my module 1)

m2.py:

def info():
    print(my module 2)

demo.py:

# 法一:import 包名.模块名
import bag.m1
bag.m1.info()  # my module 1

# 法二:from 包名 import *
from bag import *
m1.info()  # my module 1
# m2.info() # __all__列表中没有m2,报错

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!