python—模块

栏目: Python · 发布时间: 7年前

内容简介:python—模块
  • 模块是一组 Python 代码的集合,可以使用其他模块,也可以被其他模块使用。
  • 涉及到概念 包(Package) 和 模块(Module)

  • 创建自己的模块时,要注意:

    • 模块名要遵循Python变量命名规范,不要使用中文、特殊字符;
    • 模块名不要和系统模块名冲突,最好先查看系统是否已存在该模块,检查方法是在Python交互环境执行import abc,若成功则说明系统存在此模块。

使用模块

  • 示例

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    
    ' a test module '
    
    __author__ = 'Michael Liao'
    
    import sys
    
    def test():
        args = sys.argv
        if len(args)==1:
            print('Hello, world!')
        elif len(args)==2:
            print('Hello, %s!' % args[1])
        else:
            print('Too many arguments!')
    
    if __name__=='__main__':
        test()
  • 注释:

    • 第1行注释可以让这个hello.py文件直接在Unix/Linux/Mac上运行
    • 第2行注释表示.py文件本身使用标准UTF-8编码;
    • 第4行是一个字符串,表示模块的文档注释,任何模块代码的第一个字符串都被视为模块的文档注释
    • 第6行使用 author 变量把作者写进去
  • 重点 if __name__=='__main__':

  • Python解释器把一个特殊变量 name 置为 main ,而如果在其他地方导入该hello模块时,if判断将失败,因此,这种if测试可以让一个模块通过命令行运行时执行一些额外的代码,最常见的就是运行测试.

作用域

  • Python中,是通过 _ 前缀 标记 private
  • note: python中语法没有限制 _ 开头的变量/函数!

安装第三方模块

  • pip 命令

    pip install xxx
    
  • 或者在文件中自定义路径.


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Ordering Disorder

Ordering Disorder

Khoi Vinh / New Riders Press / 2010-12-03 / USD 29.99

The grid has long been an invaluable tool for creating order out of chaos for designers of all kinds—from city planners to architects to typesetters and graphic artists. In recent years, web designers......一起来看看 《Ordering Disorder》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

在线进制转换器
在线进制转换器

各进制数互转换器

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具