python基础语法(引用第三方模块)

目录

编写自己的模块

如何引用第三方模块

-----------------------------------------

  • 使用模块

编写一个hello的模块:

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

' a test module '

__author__ = 'Michael Liao'

1行和第2行是标准注释,第1行注释可以让这个hello.py文件直接在Unix/Linux/Mac上运行,第2行注释表示.py文件本身使用标准UTF-8编码;

3行是一个字符串,表示模块的文档注释,任何模块代码的第一个字符串都被视为模块的文档注释;

4行使用__author__变量把作者写进去,这样当你公开源代码后别人就可以瞻仰你的大名;

以上就是Python模块的标准文件模板,当然也可以全部删掉不写,但是,按标准办事肯定没错

  • 引用第三方模块

 模块搜索路径

当我们试图加载一个模块时,Python会在指定的路径下搜索对应的.py文件,如果找不到,就会报错:

C:\WINDOWS\system32>python

Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.

>>> import numpy

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

ModuleNotFoundError: No module named 'numpy'

  • 怎样引入第三方模块
  • 工具一、使用包管理工具pip安装第三方模块

先要确定电脑上的pip是否可用

C:\WINDOWS\system32>python

Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.

>>> ^Z

C:\WINDOWS\system32>pip

Usage:

  pip <command> [options]

下面是通过pip来安装第三方模块

C:\WINDOWS\system32>pip install numpy

Collecting numpy

  Downloading https://files.pythonhosted.org/packages/39/58/6095ee4cb19a896a6323cf2b7b8768e42f21804338871f2231a2cd41d833/numpy-1.15.1-cp36-none-win32.whl (9.9MB)

    100% |████████████████████████████████| 9.9MB 53kB/s

Installing collected packages: numpy

Successfully installed numpy-1.15.1

You are using pip version 9.0.3, however version 18.0 is available.

You should consider upgrading via the 'python -m pip install --upgrade pip' command.

 

C:\WINDOWS\system32>python

Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.

>>> import numpy

>>>

pip一个一个安装费时费力,还需要考虑兼容性Anaconda是因为它已经内置了许多非常有用的第三方库装上Anaconda,就相当于把数十个第三方模块自动安装好了,非常简单易用

安装的python3.6.5 + Anaconda3(32位)后,期望达到的效果:

C:\> python                                             

│Python 3.6.3 |Anaconda, Inc.| ... on win32              

│Type "help", ... for more information.                 

>>> import numpy #就可以直接导入了(减少了用pip install numpy的过程)

posted @ 2018-09-07 14:57  幸福在今天  阅读(321)  评论(0)    收藏  举报