码迷,mamicode.com
首页 > 其他好文 > 详细

模块 (Module)

时间:2018-03-15 00:29:13      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:cto   erp   函数   ges   接下来   test   ted   main   path   

#1.模块概念的官网描述 —— Module

If you quit from the Python interpreter and enter it again, the definitions you have made (functions and variables) are lost. Therefore, if you want to write a somewhat longer program, you are better off using a text editor to prepare the input for the interpreter and running it with that file as input instead. This is known as creating a script. As your program gets longer, you may want to split it into several files for easier maintenance. You may also want to use a handy function that you’ve written in several programs without copying its definition into each program.

如果你从 Python 解释器退出再进入,那么你定义的所有的方法和变量就都消失了。 因此,如果你想写稍微长点的程序,比起用文本编辑器去编写程序并把保存好的文件输入解释器,公认更好的方法是创造一个脚本。随着你的程序逐渐变长,为了便于维护你也许想把它分割到几个不同的文件中。也许你想要使你已经写好的许多程序获得一个便捷的功能,而不用把已写好的定义复制到每一个程序中。

To support this, Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode).

为此,Python提供了一个方法:把这些定义放到一个文件中,以供一些脚本或交互式解释器的实例使用。这样的文件叫做模块;模块中的定义可以导入到其它模块中或主模块中(在脚本执行时可以调用的变量集位于最高级,并且处于计算器模式)。

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Within a module, the module’s name (as a string) is available as the value of the global variable __name__. For instance, use your favorite text editor to create a file called fibo.py in the current directory with the following contents:

模块是一个包含了Python定义和声明的文件,文件名就是模块名加上.py后缀。在模块中,模块名(做为一个字符串)是从全局变量 __name__那获得的。例如,你可以用自己惯用的文件编辑器在当前目录下创建一个叫fibo.py的文件,录入如下内容

# Fibonacci numbers module

def fib(n):    # write Fibonacci series up to n
    a, b = 0, 1
    while b < n:
        print(b, end=‘ ‘)
        a, b = b, a+b
    print()

def fib2(n):   # return Fibonacci series up to n
    result = []
    a, b = 0, 1
    while b < n:
        result.append(b)
        a, b = b, a+b
    return result

现在进入Python解释器,用如下命令导入这个模块

>>> import fibo

这样做不会直接把 fibo 中的函数导入当前的语义表;它只是引入了模块名fibo 。你可以通过模块名按如下方式访问这个函数.

>>> fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
‘fibo‘

If you intend to use a function often you can assign it to a local name:

如果你计划经常用这个函数,也可以给它分配一个本地名:

>>> fib = fibo.fib
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

#2.简单定义:将定义的函数、变量封装在一个.py文件中,可被其他程序导入,以调用该模块中的函数等功能。这也是使用python标准库的方法。

例1:下面是一个使用 python 标准库中模块的例子

import sys  #sys.py是python标准库中一模块,而sys.argv是一个包含命令行参数的列表。
print(‘命令行参数如下:‘)
for i in sys.argv: #遍历sys.argv列表中的内容:模块名、入参
   print(i)
print(\n\nPython 路径为:‘, sys.path, \n)
#sys.path 包含了一个 Python 解释器自动查找所需模块的路径的列表。

执行结果如下所示:

$ py sys.py parm1 parm2 #给sys.py入参:parm1、parm2
命令行参数如下:
sys.py #首先遍历打印出的是模块名sys.py
parm1
parm2
Python 路径为: [‘d:\PY1‘, ‘D:\Python\Python35\python35.zip‘, ‘D:\Python\P
ython35\DLLs‘, ‘D:\Python\Python35\lib‘, ‘D:\Python\Python35‘, ‘D:\Python\Python35\lib\site-packages‘]
___

解释:

  • 1、import sys 引入 python 标准库中的 sys.py 模块;这是引入某一模块的方法。
  • 2、sys.argv 是一个包含命令行参数的列表。
  • 3、sys.path 包含了一个 Python 解释器自动查找所需模块的路径的列表。

#3.module的导入方法:3种

  • < import >语法

-- ## import module1,module2,module3,...moduleN
-- 当解释器遇到 import 语句,如果模块在当前的搜索路径就会被导入.
-- 如想要导入模块 support,需要把命令放在脚本的顶端.
-- 搜索路径是一个解释器会先进行搜索的所有目录的列表.
-- 可以接下来使用module_name.function_name/module_name.var_name 去调用模块内部函数/变量.

#import导入语法,带入参
# *********  module_1.py  *********  
def func1( par ):
    print(‘Hello:‘,par)
    return
def func2(par):
    print(‘Goodbye:‘,par)
    return
var=‘OK!Python.‘
# *********  module_test.py  ********* 
import module_1
module_1.func1(‘Python‘)

运行结果:

$ python module_test.py
Hello:Python
----------

# import语法导入<包含交互式程序的module>,无入参
#猜数字: *********  module_guess.py  *********
def Guess():
        s=input(‘Please enter your number:>‘)
        par=(int(s))
        if par>50:
            print(‘Too high!‘)
        elif par<50:
            print(‘Too low!‘)
        elif par==50:
            print(‘Bravo!!‘)
        return()
import module_guess
#调用交互式函数函数不能带入参,注意前后格式的统一
module_1.Guess()

运行结果:

$ python module_test.py
Please enter your number:>50
Bravo!!


  • < from...import > 语法:

-- from modname import name1[, name2[, ... nameN]]
-- Python的from语句让你从模块中导入一个指定的部分到当前命名空间中.

# *********  module_1.py  *********
def func1( par ):
    print(‘Hello:‘,par)
    return
def func2(par):
    print(‘Goodbye:‘,par)
    return
var=‘OK!Python.‘
# *********  module_test0.py  ********* 
from module_1 import func1,func2,var
func1(‘Python‘)  #此语法中,函数/变量可直接调用.
func2(‘Python‘)
print(var) #直接调用变量var并无返回,所以使用print或其它形式展示.

运行结果:

$ py module_test0.py
Hello: Python
Goodbye: Python
OK!Python.

‘‘‘from...import 与 import语法区别:
① import将 module文件内所有(函数/变量)一次性导入当前空间,然后随你需要调用.
② from...import只将你指定(函数/变量)导入当前空间
③ 二者调用(函数/变量)的格式不同.‘‘‘

  • < from...import* >

-- from modname import *
-- 把一个模块的所有内容一次性全部导入到当前空间(但是那些由单一下划线_开头的名字不在此例).
-- 尽量避免使用from...import*语法.

#例:
# *********  module_1.py  *********
def func1( par ):
    print(‘Hello:‘,par)
    return
def func2(par):
    print(‘Goodbye:‘,par)
    return
var=‘OK!Python.‘
#module_test00.py
from module_1 import*
func1(‘python‘)
func2(‘python‘)
print(var)

运行结果:

$ py module_test00.py
Hello: python
Goodbye: python
OK!Python.


PS:

1、如果你打算经常使用一个函数,你可以把它赋给一个本地的名称

#例:
# *********  module_1.py  *********
def func1( par ):
    print(‘Hello:‘,par)
    return
def func2(par):
    print(‘Goodbye:‘,par)
    return
var=‘OK!Python.‘
import module_1
module_1.func1(‘Python‘)

f=module_1.func1  #将 模块调用函数名赋予一个 本地函数名:f
f(‘Javascript‘) #为本地函数名f入参

运行结果:

$ py f.py
Hello: Python
Hello: Javascript


2、**** 当前模块的字符表 ****

处在 <当前模块的字符表> 内的(函数/变量)可以直接静态访问

1from module_1 import func1
#<from...import name1,name2,...nameN> 会将所有的你指定的name的(函数/变量)名都导入到<当前模块的字符表>
#但这种方法不会导入 模块名,所以用 print(dir(module_1))验证会报错,显示‘module_1‘未定义.
func_1(‘Python‘) #接下来可以直接访问,不用前缀 modulename2from module_1 import*
#此方法同例1
func_1(‘Python‘)
func_2(‘Javascript‘) 
#运行结果:  Hello:Python    Goodbye:Javascript
3import module_1
# import只把导入模块的名字‘module_1‘写入<当前模块的字符表>,而它自身内部的(函数/变量)名都没写入
module_1.func1(‘Python‘) #所以想要调用模块内函数需要前缀 modulename
module_1.func_2(‘Javascript‘)

模块 (Module)

标签:cto   erp   函数   ges   接下来   test   ted   main   path   

原文地址:https://www.cnblogs.com/deepblue775737449/p/8570880.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!