Modules and packages in the Day5-python

Source: Internet
Author: User

Module 1. What is a module
        最常见的场景,一个模块就是包含一组功能的python文件,例如module.py,模块名是module        可以使用import module,四个通用类别:        1、使用python编写的.py文件        2、已被编译为共享库或DLL的C或C++扩展        3、把一系列模块组织到一起的文件夹(注:文件夹下有一个__init__.py文件,改文件称之为包)        4、使用C编写并链接到python解释器的内置模块
2. Why use the module
1、从文件级别组织程序,更方便管理2、拿来主义,提升开发效率
3. How to use the module
1、第一次导入模块,会发生3件事,重复导入只会引用之前加载好的结果            1.产生一个新的名称空间            2.运行Spam.py代码,产生的名字都存放于1的名称空间中,运行过程中global关键字指向的就是该名称空间            3.在当前名称空间拿到一个名字spam,改名字指向1的名称空间                引用spam.py中名字的方式:spam.名字             强调:被导入的模块在执行过程中使用自己独立的名称空间作为全局名称空间        2、其别名:import spam as sm        3、一行导入多个模块 import time,os,sys
4. How to use module from module name Import name
优点:引用时不用加前缀,简单缺点:容易与当前名称空间的名字冲突from spam import * # *包含除了下划线开头意外所有的名字                   #如果定义了__all__=[],则只导入数组中的名字。
Two uses of 5.python files:
1.当作脚本文件执行: __name__ == ‘__main__‘2.当作模块被导入使用:__name__ == ‘模块名‘        控制:            if __name__ == ‘__main__‘:                paas
6. Module load Path order (lookup order)
内存---》内置---》sys.path   sys.path.append()
Package 1, what is a package
包就是一个包含了__init__.py文件的文件夹(可以往这个文件夹放一堆模块)在python3中,即使包下没有__init__.py文件,import 包仍然不会报错,而在python2中,包下一定要有该文件,否则import 包报错创建包的目的不是为了运行,而是被导入使用,记住,包只是模块的一种形式而已,包的本质就是一种模块
2, why to use the package
包的本质就是一个文件夹,那么文件夹唯一的功能就是将文件组织起来随着功能越写越多,我们无法将所以功能都放到一个文件中,于是我们使用模块去组织功能,而随着模块越来越多,我们就需要用文件夹将模块文件组织起来,以此来提高程序的结构性和可维护性
3. Precautions
#1.关于包相关的导入语句也分为import和from ... import ...两种,但是无论哪种,无论在什么位置,在导入时都必须遵循一个原则:凡是在导入时带点的,点的左边都必须是一个包,否则非法。可以带有一连串的点,如item.subitem.subsubitem,但都必须遵循这个原则。但对于导入后,在使用时就没有这种限制了,点的左边可以是包,模块,函数,类(它们都可以用点的方式调用自己的属性)。#2、import导入文件时,产生名称空间中的名字来源于文件,import 包,产生的名称空间的名字同样来源于文件,即包下的__init__.py,导入包本质就是在导入该文件#3、包A和包B下有同名模块也不会冲突,如A.a与B.a来自俩个命名空间

Modules and packages in the Day5-python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.