第九章 Python自定义模块及导入方法

简介:

9.1 自定义模块

自定义模块你已经会了,平常写的代码放到一个文件里面就是啦!

例如,写个简单的函数,作为一个模块:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/usr/bin/python
# -*- coding: utf-8 -*-
def  func(a, b):
    return  *  b
class  MyClass:
    def  __init__( self , a, b):
         self .a  =  a
         self .b  =  b
    def  method( self ):
         return  self .a  *  self .b
导入模块:
>>>  import  test
>>> test.func( 2 2 )
4
>>> c  =  test.MyClass( 2 2 )
>>> c.method()
4

是不是很简单!是的,没错,就是这样。

需要注意的是,test就是文件名。另外,模块名要能找到,我的是在当前目录下。

有时经常from...import...,这又是啥呢,来看看:

1
2
3
4
5
6
7
8
9
10
>>>  from  test  import  func, MyClass   # 多个函数或类以逗号分隔
>>> test.func( 2 2 )
Traceback (most recent call last):
   File  "<stdin>" , line  1 in  <module>
NameError: name  'test'  is  not  defined
>>> func( 2 2 )
4
>>> c  =  MyClass( 2 2 )
>>> c.method()
4

看到了吧!如果你不想把模块里的函数都导入,就可以这样。一方面避免导入过多用不到的函数增加负载,另一方面引用时可不加模块名。

如果想调用不加模块名,也想导入所有模块,可以这样:

1
2
3
4
5
6
>>>  from  test  import  *
>>> func( 2 2 )
4
>>> c  =  MyClass( 2 2 )
>>> c.method()
4

使用个星号就代表了所有。

提醒:在模块之间引用也是同样的方式。


博客地址:http://lizhenliang.blog.51cto.com

QQ群:323779636(Shell/Python运维开发群


9.2 作为脚本来运行程序

所有的模块都有一个内置属性__name__,如果import一个模块,那么模块的__name__属性返回值一般是文件名。如果直接运行Python程序,__name__的值将是一个"__mian__"。

举例说明,根据上面程序做一个测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/python
# -*- coding: utf-8 -*-
def  func(a, b):
    return  *  b
class  MyClass:
    def  __init__( self , a, b):
         self .a  =  a
         self .b  =  b
    def  method( self ):
         return  self .a  *  self .b
print  __name__
 
# python test.py
__main__

与预期一样,打印出了“__main__”,再创建一个test2.py,导入这个模块:

1
2
3
4
5
6
#!/usr/bin/python
# -*- coding: utf-8 -*-
import  test
 
# python test2.py
test

打印出了模块名,这个结果输出就是test.py中的print __name__。

所以,我们在test.py里面判断下__name__值等于__main__时说明在手动执行这个程序:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/python
# -*- coding: utf-8 -*-
def  func(a, b):
    return  *  b
class  MyClass:
    def  __init__( self , a, b):
         self .a  =  a
         self .b  =  b
    def  method( self ):
         return  self .a  *  self .b
if  __name__  = =  "__main__" :
    print  "我在手动执行这个程序..."
    
# python test.py
我在手动执行这个程序...

此时再运行test2.py试试,是不是打印为空!明白了吧!

9.3 安装第三方模块

在Python中安装外部的模块有几种方式:

1)下载压缩包,通过setuptools工具安装,这个在第一章Python基础知识里面用到过。推荐下载地址:http://pypi.python.org

2)easy_install工具安装,也依赖setuptools。

3)pip工具安装。推荐使用这个方式。

4)直接将压缩包解压到Python模块目录。但常常会出现import失败,不推荐。

5)在Windows下,除了上面几种方式以外,可以直接下载exe文件点击一步步安装。

pip与easy_install安装方式类似,主要区别在于easy_install不支持卸载软件,而pip支持。

推荐使用pip命令安装,简单方便。如果安装失败可以按顺序这么尝试:方式1 --> 方式2 --> 方式4

以安装setuptools举例上面几种安装方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
方式 1
# wget https://pypi.python.org/packages/32/3c/e853a68b703f347f5ed86585c2dd2828a83252e1216c1201fa6f81270578/setuptools-26.1.1.tar.gz
# tar zxvf setuptools-26.1.1.tar.gz
# cd setuptools-26.1.1
# python setup.py install
方式 2
# easy_install setuptools
方式 3
# pip install setuptools
# pip uninstall setuptools  # 卸载
# pip search setuptools  # 搜索
方式 3
cp  - rf setuptools - 26.1 . 1  / usr / local / lib / python2. 7 / dist - packages

9.4 查看模块帮助文档

前面几个章节已经使用几个内置模块了,比如collections、itertools等,导入与上面一样,这里不再过多说明了。

1)help()函数

当一个模块对其语法不了解时,可以查看帮助,以collections举例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
>>>  import  collections    
>>>  help (collections)
Help  on module collections:
NAME
   collections
FILE
   / usr / lib / python2. 7 / collections.py
MODULE DOCS
   http: / / docs.python.org / library / collections   # 注意:这里是这个模块的帮助文档,很详细的哦!
CLASSES
    __builtin__. dict (__builtin__. object )
         Counter
         OrderedDict
         defaultdict
    __builtin__. object
         _abcoll. Callable
         _abcoll.Container
     ......

使用help()就能查看这个模块的内部构造,包括类方法、属性等信息。

也可以再对某个方法查看其用法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
>>>  help (collections.Counter())    
Help  on Counter  in  module collections  object :
class  Counter(__builtin__. dict )
      |   Dict  subclass  for  counting hashable items.  Sometimes called a bag
      |   or  multiset.  Elements are stored as dictionary keys  and  their counts
      |  are stored as dictionary values.
     
      |  >>> c  =  Counter( 'abcdeabcdabcaba' )   # count elements from a string
     
      |  >>> c.most_common( 3 )                 # three most common elements
      |  [( 'a' 5 ), ( 'b' 4 ), ( 'c' 3 )]
      |  >>>  sorted (c)                        # list all unique elements
      |  [ 'a' 'b' 'c' 'd' 'e' ]
      |  >>> ''.join( sorted (c.elements()))    # list elements with repetitions
      |   'aaaaabbbbcccdde'
      |  >>>  sum (c.values())                  # total of all counts
      |   15
     
      |  >>> c[ 'a' ]                           # count of letter 'a'
......

一般里面都是举例说明,可快速帮助我们回忆使用方法。

2)dir()函数查看对象属性

这个在前面也用到过,能看到对象的方法、属性等信息:

1
2
     >>>  dir (collections)    
     [ 'Callable' 'Container' 'Counter' 'Hashable' 'ItemsView' 'Iterable' 'Iterator' 'KeysView' 'Mapping' 'MappingView' 'MutableMapping' 'MutableSequence' 'MutableSet' 'OrderedDict' 'Sequence' 'Set' 'Sized' 'ValuesView' '__all__' '__builtins__' '__doc__' '__file__' '__name__' '__package__' '_abcoll' '_chain' '_class_template' '_eq' '_field_template' '_get_ident' '_heapq' '_imap' '_iskeyword' '_itemgetter' '_repeat' '_repr_template' '_starmap' '_sys' 'defaultdict' 'deque' 'namedtuple' ]

3)github上查看模块用法

Python官方模块下载地址http://pypi.python.org,所有的模块在这里都有。

打开网站后,在搜索框搜索你的模块名,在结果找到模块名点进去,会有一个 Home Page的连接,Python大多数模块都是托管在github上面,这个链接就是这个模块在github上面的地址,点击后跳转到github对应的模块页面,里面也有很详细模块使用方法。

9.5 导入模块新手容易出现的问题

还有一个新手经常犯的问题,写一个模块,比如使用itertools模块,为了说明这个测试文件是这个模块,就把文件名写成了这个模块名,于是就造成了下面错误:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/python
# -*- coding: utf-8 -*-
import  collections
=  collections.Counter()
for  in  "Hello world!" :
    c[i]  + =  1
print  c
 
# python collections.py
Traceback (most recent call last):
   File  "collections.py" , line  3 in  <module>
     import  collections
   File  "/home/user/collections.py" , line  4 in  <module>
     =  collections.Counter()
AttributeError:  'module'  object  has no attribute  'Counter'

抛出异常,明明在解释器里面可以正常导入使用啊,怎么会提示没Counter属性呢,问题就出现你的文件名与导入的模块名重名,导致程序import了这个文件,上面讲过文件名就是模块名。所以文件名不要与引用的模块名相同。

还有一个使用方法也说明下,使用as关键字设置模块别名,这样使用中就不用输入那么长的模块名了,按照上面的例子,把名字先改成collections1.py,做测试:

1
2
3
4
5
6
7
8
9
10
#!/usr/bin/python
# -*- coding: utf-8 -*-
import  collections as cc
=  cc.Counter()
for  in  "Hello world!" :
    c[i]  + =  1
print  c
 
# python collections1.py
Counter({ 'l' 3 'o' 2 '!' 1 ' ' 1 'e' 1 'd' 1 'H' 1 'r' 1 'w' 1 })



本文转自 李振良OK 51CTO博客,原文链接:http://blog.51cto.com/lizhenliang/1866390,如需转载请自行联系原作者
相关文章
|
3天前
|
人工智能 Python
【Python实用技能】建议收藏:自动化实现网页内容转PDF并保存的方法探索(含代码,亲测可用)
【Python实用技能】建议收藏:自动化实现网页内容转PDF并保存的方法探索(含代码,亲测可用)
21 0
Python
20 0
|
3天前
|
开发者 Python
Python的os模块详解
Python的os模块详解
15 0
|
6天前
|
数据挖掘 API 数据安全/隐私保护
python请求模块requests如何添加代理ip
python请求模块requests如何添加代理ip
|
8天前
|
存储 关系型数据库 MySQL
Python搭建代理IP池实现存储IP的方法
Python搭建代理IP池实现存储IP的方法
|
8天前
|
Python
Python动态IP代理防止被封的方法
Python动态IP代理防止被封的方法
|
8天前
|
测试技术 Python
Python 有趣的模块之pynupt——通过pynput控制鼠标和键盘
Python 有趣的模块之pynupt——通过pynput控制鼠标和键盘
|
8天前
|
Serverless 开发者 Python
《Python 简易速速上手小册》第3章:Python 的函数和模块(2024 最新版)
《Python 简易速速上手小册》第3章:Python 的函数和模块(2024 最新版)
40 1
|
8天前
|
数据采集 存储 安全
python检测代理ip是否可用的方法
python检测代理ip是否可用的方法
|
9天前
|
数据可视化 测试技术 Python
在Python和R中使用交叉验证方法提高模型性能
在Python和R中使用交叉验证方法提高模型性能
20 0