首页 > 编程语言 > 详细

python全栈闯关--20-模块和包

时间:2020-04-09 12:24:10      阅读:70      评论:0      收藏:0      [点我收藏+]

模块

mymoudle

# -*- coding:utf-8 -*-
print(form my_moudle.py)

money=1000

def read1():
    print("my_moudle read1",money)

def read2():
    print("my_moudle read2")

def change():
    global money
    money = 0

 

1、使用import导入模块

import sys
import my_module
import my_module
import my_module
import my_module
print(sys.path)
print(sys.modules.keys())

导入模块,会按照当前路径,pytchon解释器的方式去寻找包的路径。

多次导入包,不会重复导入。会根据sys.mmodules里面的值进行判别,包是否已经导入。

 

money=10
print(m.money)
print(money)

包有自己的命名空间,不与当前目录冲突

 

def read1():
    print(this is in main)

read1()
m.read1()

函数也不与当模块中冲突

 

m.change()
print(money)
m.read1()

虽然moudle中,定义了全局变量,但是修改的还是moudle中的值。

 

导入模块时,第一步,创建模块的命名空间,如果定义了global,引用的依然是命名空间中的模块;

第二部,执行模块中的代码

 

使用import as 别名来导入模块

导入后,可以使用别名来进行操作,以到达简化代码的目的。

可以通过参数,判断导入不同的参数,简化代码

2、from import

from my_module import read1
def read1():
    print(this is in main)
money = 10
read1()

本函数中的read1覆盖了导入的read1

from my_module import read1
# def read1():
#     print(‘this is in main‘)
money = 10
read1()

虽然修改了本模块中的money,但是调用的依然是my_module中的值

from my_module import read1
from my_module import read2
def read1():
    print(this is in main)
# money = 10
# read1()

read2()

read2中引用了read1,执行结果使用的money依然是模块中的money

 

__all__参数

__all__参数与from import * 组合使用,用于过滤导入的数据。只有子all中的函数、变量才会被导入

from my_module import *
print(read1)
print(read2)
print(money)
print(change)

没加all参数前,可以导入全部函数、变量

在module中添加all参数后

__all__ = [read1, read2]

```

<function read1 at 0x000001F2D1CBE0D0>
<function read2 at 0x000001F2D1CBE1E0>
print(money)
NameError: name ‘money‘ is not define

```

就只导入了read1和read2

 

 

import time,day21.imlib as i
import importlib
time.sleep(30)
importlib.reload(i)
i.func1()

如果导入包后,修改了模块,结果不会反应到已经加载的模块中,此时,就需要使用importlib来重新加载包。

如上例子中,如果在休眠的30秒内,修改了imlib,最终执行的不会是罪行的imlib。

使用importlib.reload重新加载后,更新到最新的代码。

python全栈闯关--20-模块和包

原文:https://www.cnblogs.com/zxw-xxcsl/p/12665960.html

(1)
(1)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!