day 3 模块

时间:2021-09-30 10:07:58

1.系统自带模块  xxx.py 文件 就是模块

### 模块存放位置
In [1]: import os In [2]: os.__file__
Out[2]: '/usr/lib/python3.5/os.py'
python@ubuntu:~$ cd /usr/lib/python3.5/
python@ubuntu:/usr/lib/python3.5$ ls
abc.py html selectors.py
aifc.py http shelve.py
antigravity.py idlelib shlex.py
argparse.py imaplib.py shutil.py
ast.py imghdr.py signal.py
asynchat.py importlib _sitebuiltins.py
asyncio imp.py sitecustomize.py

2.第三方模块

####   安装第三方模块
python@ubuntu:~$ sudo pip install pycharm

3.自定义模块

  1)版本1:import sendmsg

####   sendmsg.py 

def test1():
print("----test1") def test2():
print("----test2") test1()
test2()
#########   main.py
import sendmsg
sendmsg.test1()
sendmsg.test2()
####运行结果   python3 main.py
----test1
----test2
.
├── main.py
├── __pycache__
│?? └── sendmsg.cpython-35.pyc
c语言写的python解释器 3.5版本 字节码
├── recvmsg.py
└── sendmsg.py

    day 3 模块

  2)版本2: from sendmsg import test1,test2

### main.py
from sendmsg import test1,test2
test1()
test2()

  3)版本3:导入1000个方法

### main.py
from sendmsg import * #不推荐使用,切记
#from recvmsg import * #recvmsg模块有可能有test1()方法 test1()
test2()
test2()
test2()
####  main.py
import sendmsg
sendmsg.test1()
sendmsg.test2()
sendmsg.test2()
sendmsg.test2()

  4)版本4: as  针对模块名字较长的使用

In [1]: import time as tt

In [2]: tt.time()
Out[2]: 1511591526.7604477

4.__name__变量

  自己测试,执行test1()

  老板导入sendmsg.py 模块,不执行test1()

#### sendmsg.py  模块
def test1():
print("----test1") def test2():
print("----test2") test1()
test2() python@ubuntu:~/pythonS6/python基础092/06-模块$ python3 sendmsg.py
----test1
----test2
###  main.py
import sendmsg
sendmsg.test1()
sendmsg.test2() python@ubuntu:~/pythonS6/python基础092/06-模块$ python3 main.py
----test1
----test2
----test1
----test2

  2)版本2:什么是__name__变量

python@ubuntu:~/pythonS6/python基础092/06-模块$ cat sendmsg.py 

def test1():
print("----test1") def test2():
print("----test2") print(__name__)
test1()
test2()
python@ubuntu:~/pythonS6/python基础092/06-模块$ python3 sendmsg.py
__main__
----test1
----test2 python@ubuntu:~/pythonS6/python基础092/06-模块$ python3 main.py sendmsg #打印的是模块名
----test1
----test2
----test1
----test2

  3)版本3:

def test1():
print("----test1") def test2():
print("----test2") #print(__name__) #__main__
if __name__ == "__main__": #如果自己测试,执行下面的语句 #如果老板导入模块,不执行
test1()
test2()
python@ubuntu:~/pythonS6/python基础092/06-模块$ python3 sendmsg.py
----test1
----test2
python@ubuntu:~/pythonS6/python基础092/06-模块$ python3 main.py
----test1
----test2

  总结:

  • 可以根据__name__变量的结果能够判断出,是直接执行的python脚本还是被引入执行的,从而能够有选择性的执行测试代码

5.程序大体框架

class Xxx(object):
pass def xxx():
pass def main():
pass if __name__ == "__main__": #别人调用上面的方法不执行
main() #自己测试,执行