• python-模块


    1. 导入模块

     import math

         你可以认为math就是一个指向已导入模块的变量,通过该变量,我们可以访问math模块中所定义的所有公开的函数、变量和类 

         如果我们只希望导入用到的math模块的某几个函数,而不是所有函数,可以用下面的语句:

     from math import pow, sin, log

    2. python中动态导入模块

        Python 2.6/2.7提供了json 模块,但Python 2.5以及更早版本没有json模块,不过可以安装一个simplejson模块,这两个模块提供的函数签名和功能都一模一样。

    try:
        import json
    except ImportError:
        import simplejson as json
    print json.dumps({'python':2.7})

    利用ImportError错误,我们经常在Python中动态导入模块:

     StringIO 是纯Python代码编写的,而 cStringIO 部分函数是 C 写的,因此 cStringIO 运行速度更快。

    try:
        from cStringIO import StringIO
    except ImportError:
        from StringIO import StringIO

    3. python之使用__future__

    Python的新版本会引入新的功能,但是,实际上这些功能在上一个老版本中就已经存在了。要“试用”某一新的特性,就可以通过导入__future__模块的某些功能来实现。

    例如,Python 2.7的整数除法运算结果仍是整数:

             >>> 10 / 3

           3

    但是,Python 3.x已经改进了整数的除法运算,“/”除将得到浮点数,“//”除才仍是整数:
    >>> 10 / 3
    3.3333333333333335
    >>> 10 // 3
    3

    要在Python 2.7中引入3.x的除法规则,导入__future__division

    >>> from __future__ import division
    >>> print 10 / 3
    3.3333333333333335

    当新版本的一个特性与旧版本不兼容时,该特性将会在旧版本中添加到__future__中,以便旧的代码能在旧版本中测试新特性

    Python 3.x中,字符串统一为unicode,不需要加前缀 u,而以字节存储的str则必须加前缀 b。请利用__future__unicode_literals在Python 2.7中编写unicode字符串。

    from __future__ import unicode_literals
    s = 'am I an unicode?'
    print isinstance(s, unicode)

    4. 安装第三方模块

        * easy_install

        * pip

        https://pypi.python.org/

     
    
    
  • 相关阅读:
    Java类加载器回顾
    2018第24周总结
    JUC类图
    CopyOnWrite 策略
    Python导入模块的几种姿势
    查看linux接口进出口流量的命令;linux 网络监控;流量监控
    jenkins修改日志级别方法
    top命令查看线程信息和jstack使用介绍
    How to force immediate stop of threads in Jmeter servers如何在jmeter执行完,立即停止jmeter
    pycharm支持react
  • 原文地址:https://www.cnblogs.com/ting152/p/12928766.html
Copyright © 2020-2023  润新知