最新消息:

少儿Python基础(11)​ | 模块

Python 少儿编程 2066浏览 0评论
Python少儿编程02

可爱的小朋友们,今天我们一起来学习一下Python模块吧

01

什么是模块?

模块(Module),是一个 Python 文件,以 .py 结尾,是封装组织代码,根据不同功能将代码分割成不同的模块,这样每个模块是独立的。模块可以实现代码的重用。

 

模块可以被项目中的其他模块、一些脚本甚至是交互式的解析器所使用,它可以被其他程序引用,从而使用该模块里的函数等功能。

模块是高级封装,那么常见的封装有哪些呢?

1:容器(列表,元组,字符串,字典)–>对数据的封装

2:函数–>语句的封

3:类–>方法和属性的封装

4:模块–>模块就是程序

02

模块分类

在Python中模块分为以下几种:

1:系统内置模块:例如:sys、time、json模块等等;

2:自定义模块:自定义模块是自己写的模块,对某段逻辑或某些函数进行封装后供其他函数调用。

注意:自定义模块的命名一定不能和系统内置的模块重名

3:第三方的开源模块:这部分模块可以通过pip install进行安装,有开源的代码

03

导入模块方法

第一种:import 模块名

第二种:from 模块名 import 函数名

第三种:import 模块名 as 新名字  (推荐使用)

少儿Python​ | 模块

新建一个模块

#新建一个模块:TemperatureConversio.py。c2f和 f2c是希望被重复利用的代码
#摄氏度(C)和华氏度(F)之间的换算关系为:
#F=C×1.8+32
#C=(F-32)÷1.8
def c2f(cel):   #摄氏度-->华氏度
   fah=cel*1.8+32
   return fah
def f2c(fah): #华氏度-->摄氏度
   cel=(fah-32)/1.8
   return cel

少儿Python​ | 模块

导入模块

#calc.py
#方法一:import 模块名
import TemperatureConversion #命名空间
print("32摄氏度=%.2f华氏度" %TemperatureConversion.c2f(32))
print("99华氏度=%.2f摄氏度" %TemperatureConversion.f2c(99))
#方法二:from 模块名 import 函数名
from TemperatureConversion import c2f,f2c
print("32摄氏度=%.2f华氏度" %c2f(32))
print("99华氏度=%.2f摄氏度" %f2c(99)
#方法三:import 模块名 as 新名字  (推荐使用)
import TemperatureConversion as tc
print("32摄氏度=%.2f华氏度" %tc.c2f(32))
print("99华氏度=%.2f摄氏度" %tc.f2c(99))

04

模块中的__name__

当一个程序导入另一个模块时,实际上会把这个模块从头到尾执行一遍。这样会带来个一个问题:

一般情况下,我们在写完模块的时候,会对模块进行单独的测试,会在后面写一个test()函数对这个模块功能进行测试。如果不把这些测试程序去除,在被其它程序导入时也会执行了这些测试程序,显然这是我们不希望看到的。

解决问题关键:

让python知道该模块是作为程序运行还是导入到其它程序中的。

使用 if __name__==’__main__’  可以在不删除模块内测试代码的前提下解决了问题

__name__分析:

如果在主程序(TemperatureConversio.py)中使用 __name__,会得到 ‘__main__’

如果在作为导入模块中的程序如calc.py调用__name__,会得到模块名字(TemperatureConversio)

#模块代码
def c2f(cel):   #摄氏度-->华氏度
    fah=cel*1.8+32
    return fah
def f2c(fah): #华氏度-->摄氏度
    cel=(fah-32)/1.8
    return cel
    #这里测试对前面函数调用,若成功则没有问题
def test():
     print("测试,0摄氏度=%.2f华氏度" %c2f(0));
     print("测试,0华氏度=%.2f摄氏度" %f2c(0));
if __name__=="__main__":  #作为主程序
     test()

05

搜索路径

python模块导入,需要一个路径搜索的过程

如 导入hello.py文件,python会在预定好的搜索路径(一个列表/一组目录)找hello.py模块文件,如果有,则导入文件,如果没有则导入失败。可以通过sys.path显示出来预定好的搜索路径

模块搜索路径存储在 sySTEM 模块的 sys.path 变量中。变量里包含当前目录,PYTHONPATH和由安装过程决定的默认目录。

>>> import sys
>>> sys.path
   #从以下搜索相应模块 ,如果找到则导入,如果没有找到,则报错   
['F:/pythondemo', 'C:\Users\HP\AppData\Local\Programs\Python\Python36\Lib\idlelib', 'C:\Users\HP\AppData\Local\Programs\Python\Python36\python36.zip', 'C:\Users\HP\AppData\Local\Programs\Python\Python36\DLLs', 'C:\Users\HP\AppData\Local\Programs\Python\Python36\lib', 'C:\Users\HP\AppData\Local\Programs\Python\Python36', 'C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages']
#保存模块最佳位置   'C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages'
>>> import TemperatureConversion 
Traceback (most recent call last):
  File "<pyshell#274>", line 1, in <module>
    import TemperatureConversion
ModuleNotFoundError: No module named 'TemperatureConversion'
>>> sys.path.append("F:pythondemoshe_huadu")  #比如在IDLE要导入某个模块,可以把它加到搜索路径
>>> sys.path
['F:/pythondemo', 'C:\Users\HP\AppData\Local\Programs\Python\Python36\Lib\idlelib', 'C:\Users\HP\AppData\Local\Programs\Python\Python36\python36.zip', 'C:\Users\HP\AppData\Local\Programs\Python\Python36\DLLs', 'C:\Users\HP\AppData\Local\Programs\Python\Python36\lib', 'C:\Users\HP\AppData\Local\Programs\Python\Python36', 'C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages', 'F:\pythondemo\she_huadu']
>>> import TemperatureConversion
>>> TemperatureConversion.c2f(32)
89.6
>>

06

Python中的包

包是一个分层次的文件目录结构,它定义了一个由模块及子包,和子包下的子包等组成的 Python 的应用环境。

简单地说:包是把模块分类放在不同的文件夹,然后把文件夹位置告诉python即可。但该文件夹下必须存在 __init__.py 文件, 该文件的内容可以为空。__init__.py 用于标识当前文件夹是一个包。

创建包方法:

1:创建一个文件夹,用于存放相关的模块,文件夹的名字即包的名字

2:在文件夹中创建一个__init__.py模块文件,内容可以为空

3:将相关的模块放入文件夹中

少儿Python​ | 模块

图1 创建包

少儿Python​ | 模块

如何导入包文件

语法:

包名.模块名

import M1.TemperatureConversion as tc
print("32摄氏度=%.2f华氏度" %tc.c2f(32))
print("99华氏度=%.2f摄氏度" %tc.f2c(99))

07

如何快速掌握一个模块

如何快速掌握一个模块(以timeit为例)

1:利用IDLE导入模块

import timeit

2:调用__doc__属性,可以查看模块的简介

print(timeit.__doc__)

3:可能需要知道这个模块里面定义了哪些变量/函数/类,可用dir()方法

dir(timeit)

4:需要过滤掉一些东西

__all__  #显示这个模块可以供外界调用的所有东西

timeit.__all__    #返回列表[类,接口函数1,接口函数2,接口函数3]

注意:

<1>并不是所有的模块都有__all__属性,__all__包含的内容是希望外部调用的函数/类。如果一个模块涉及了__all__属性,那么可以使用form timeit import *来导入命名空间,只有__all__属性这里的名字才会被导入。

<2>若没有涉及__alll__属性,from 模块名 import *会把所有以下划线开头的名字导入到当前命名空间。所以建议在编写模块时,对外提供接口函数类都涉及__all__属性的列表里面去

5:__file__属性指明该模块的源代码所在的位置

timeit.__file__

6:

常用help()内置函数

help(timeit)  #比官方文档简单些,快速知道各个函数的用法

>>> import timeit
>>> timeit.__doc__
"Tool for measuring execution time of small code snippets.nnThis module avoids a number of common traps for measuring executionntimes.  See also Tim Peters' introduction to the Algorithms chapter innthe Python Cookbook, published by O'Reilly.nnLibrary usage: see the Timer class.nnCommand line usage:n    python timeit.py [-n N] [-r N] [-s S] [-t] [-c] [-p] [-h] [--] [statement]nnOptions:n  -n/--number N: how many times to execute 'statement' (default: see below)n  -r/--repeat N: how many times to repeat the timer (default 3)n  -s/--setup S: statement to be executed once initially (default 'pass').n                Execution time of this setup statement is NOT timed.n  -p/--process: use time.process_time() (default is time.perf_counter())n  -t/--time: use time.time() (deprecated)n  -c/--clock: use time.clock() (deprecated)n  -v/--verbose: print raw timing results; repeat for more digits precisionn  -u/--unit: set the output time unit (usec, msec, or sec)n  -h/--help: print this usage message and exitn  --: separate options from statement, use when statement starts with -n  statement: statement to be timed (default 'pass')nnA multi-line statement may be given by specifying each line as anseparate argument; indented lines are possible by enclosing annargument in quotes and using leading spaces.  Multiple -s options arentreated similarly.nnIf -n is not given, a suitable number of loops is calculated by tryingnsuccessive powers of 10 until the total time is at least 0.2 seconds.nnNote: there is a certain baseline overhead associated with executing anpass statement.  It differs between versions.  The code here doesn't trynto hide it, but you should be aware of it.  The baseline overhead can benmeasured by invoking the program without arguments.nnClasses:nn    TimernnFunctions:nn    timeit(string, string) -> floatn    repeat(string, string) -> listn    default_timer() -> floatnn"
>>> print(timeit)
<module 'timeit' from 'C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\timeit.py'>
>>> print(timeit.__doc__)
   >>> dir(timeit)
['Timer', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_globals', 'default_number', 'default_repeat', 'default_timer', 'dummy_src_name', 'gc', 'itertools', 'main', 'reindent', 'repeat', 'sys', 'template', 'time', 'timeit']
>>> 
>>> timeit.__all__
['Timer', 'timeit', 'repeat', 'default_timer']
>>> 
>>> timeit.__file__
'C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\timeit.py'
>>> 
>>> help(timeit)

THE END

您必须 登录 才能发表评论!