python教学设计

| 收藏本文 下载本文 作者:unnme

以下是小编整理的python教学设计(共含16篇),欢迎阅读分享,希望对您有所帮助。同时,但愿您也能像本文投稿人“unnme”一样,积极向本站投稿分享好文章。

python教学设计

篇1:Python精选教学心得

最近这段时间我们学习了很多内容,增长了很多关于Python的知识,万事万物是相通的,正如学习新的知识就像吃饭一样。

吃多了就会消化不良,反映到学习上也是一样,不知各位最近的感觉怎样,反正学记是需要一些时间好好消化,掌握到手中,为下一步的知识补齐缺口。

接下来,学记和大家一起回顾一下最近学习的内容,循序渐进,循序渐进。

分支结构

分支结构就像上图一样,是用来选择道路的。

所用的关键字是

If elif else

这三个词的意思分别是

如果 否则如果 其他的

分支语句的写法需要将与关键字与关键字对齐

循环结构

循环结构应用于一些重复的进程

通常我们只接触两种循环

for-in循环 和 while循环

for-in循环适用于

确切的知道到底循环几次

while循环适用于

不知道到底有几次循环

此时要搭配bool 来进行

即 True 和 Flase

关键字

关键字的熟练运用对于今后的开发工作

有非常重要的作用,但这么多关键字我们不能去死记硬背

只有在一个一个代码的验证当中去熟悉去掌握

那样是最可靠的

def 设置模组

len 计算字符串长度

capitalize 获得字符串首字母大写的拷贝

upper 获得字符串变大写后的拷贝

find 从字符串中查找子串所在位置

index 与find类似但找不到子串时会引发异常

startswith 检查字符串是否以指定的字符串开头

endswith 检查字符串是否以指定的字符串结尾

center 将字符串以指定的宽度居中并在两侧填充指定的字符

rjust 将字符串以指定的宽度靠右放置左侧 填充指定的字符

isdigit 检查字符串是否由数字构成

isalpha 检查字符串是否以字母构成

isalnum 检查字符串是否以数字和字母构成

append 添加元素

remove 删除元素

clear 清空元素

sorted 排序

大家可能会有些疑惑,学习这些东西真的有用吗?这些随处可见的基础方面的知识真的有用吗?

我可以非常肯定地告诉大家

有用的!

这些知识就像是建筑工地随处可见的砖石,不管这些砖石怎样的不起眼,但是没有一幢建筑可以离开砖石,学习的过程是枯燥的,不过这也正符合非常现实的一条规律。

学如逆水行舟,不进则退!

也正是因为它枯燥苦闷,学习有难度,才保证了,我们学习了这些知识以后,可以靠它们为生,在这个知识时代闯出自己的一片天!

不要放弃,绝对不要放弃!

黎明之前是最黑暗的!

为了自己的未来好好坚守吧!

青年学记 陪伴着各位青年

篇2:Python精选教学心得

python是一门非常有潜力的高级语言,历经多年的发展,其在编程上发挥着越来越大的作用。在这学期中,通过选修python课上的基础知识学习,我对python也有了一定的认识。而且,在字符串上的处理,python相对于c语言也是给程序员极大的便利。而python不仅如此,它的库也很多,正因为它强大的库,让编程变得不再艰难。但是,我认为python虽然在许多方面相对于c语言比较方便,但也有其相对于弱一点的方面,比如说for循环等方面。虽然一学期下来,我对python的学习也仅仅只是它的基础方面,但python的强大,也是足足地吸引着我,希望自己能够在不断地学习中,将python学习的更加好。

python是一门非常有潜力的高级语言,历经多年的发展,其在编程上发挥着越来越大的作用。在这学期中,通过选修python课上的基础知识学习,我对python也有了一定的认识。

在学习python的第一节课上,其对我的最初的印象就是,相较于我学习过的c语言编程,它更加的简洁。所有的变量都不需要像c语言编程那样需要提前去定义,这样给了编程者很大的自由空间与方便。如x=2,即可同时完成变量的定义与赋值。对于简化程序的代码,起到了许多的作用。而且,在字符串上的处理,python相对于c语言也是给程序员极大的便利。在c语言中,只能用字符类的数组对字符串进行相应的操作,步骤也是相对于比较繁琐的,而在python中,当我们需要创建一个字符串的时候,只需要在创建字符串的时候用“s=”就可以了。而python不仅如此,它的库也很多,正因为它强大的库,让编程变得不再艰难。我们只需要调用库中的函数,而对于函数的具体实现,也没有特殊的需求。

但是,我认为python虽然在许多方面相对于c语言比较方便,但也有其相对于弱一点的方面,比如说for循环等方面。不过也依然不会影响到python的强大,而随着近几年来的发展,python的受欢迎度也越来越高,而它的运用的领域也是越来越多,比如人工智能和大数据等领域,python都是在其中扮演者重要的角色。虽然一学期下来,我对python的学习也仅仅只是它的基础方面,但python的强大,也是足足地吸引着我,希望自己能够在不断地学习中,将python学习的更加好。

篇3:Python精选教学心得

由于我是自学Python,非科班出生,所以只能分享一些关于我的学习心得,如果有不对地方欢迎指正。

不过非科班出生虽然是一个痛点,但是在工作上,我其实不输给我其他同事,这点我倒是很有自信,而且我也统一一句话“目前互联网上的免费编程课程,足够让你成为一个合格的码农”。

编程入门

我刚开始学习编程,主要是因为自己想动手做个网站,但是由于技术原因,再加上朋友都比较忙,最后抱着“求人不如求己”的想法,干脆自学。

编程难不难?

这个问题我觉得所有认真学过的人,都一定会肯定告诉你编程不难,但是精通那是相当困难的。

如果你还没去学习,就觉得编程一定很难,那么其实你是没有资格说这句话的,任何事情一定是要去尝试后,才能这么说。

编程其实很像堆积木,然后根据需求,把东西造出来,可以是房子,也可以是桥梁。

学习编程无非运用这些积木,来创造你要的东西。

编程语言选择

这边说个题外话,关于当时编程语言的选择,很多时候我觉得不是你选择编程语言,而是编程语言选择你,也就是你的“本命编程语言”。

人的性格会影响你适合的编程语言,比如你做事有条理,喜欢定期清理房间,那么可能C语言很适合你;如果你不喜欢打扫房间,实在受不了,才打扫一次,可能你适合Java。

哈哈,开个玩笑,不过确实有这种很玄的存在。

我当时在编程语言的选择上,用了一个笨方法。

我跑到w3cschool上面,把所有编程语言的第一章都去试了一遍,看看自己喜欢哪个语言,然后就选哪个语言,如果你不知道选哪门语言,可以用我的方法试试看。

至于编程语言,没有高低之分,因为无论你学习哪门语言,你都非常有市场,而且你都能够拿到高薪,关键是哪门语言适合你,并且能够让你有兴趣学下去,能学好,这个很关键。

兴趣是学习编程最大的驱动力!

为什么是Python

说下为什么选择Python?

因为简单,Python是公认的最容易入门的编程语言,而且也是公认有发展前景的编程语言,适用于机器人、大数据、人工智商等未来高科技。

基于以上的原因,我选择Python来作为自己的入门语言,而且我觉得我适合Python这么语言。(因为我很懒)

之前有个梗,大概就是其他编程语言在讨论某个问题,怎么解决,而Python的程序员已经下班了,由此可见Python的效率。

总结:Python的语言特点就是“一气呵成,痛快如拉稀”。

学习心得

由于我是自学的,所以参考的网站比较多,小伙伴可以按照我的学习路线,一般来说不会出现什么问题。

基础:教程+视频

进阶:视频+实践

进阶pro:视频+实践+书籍+交流

基础

刚开始学习的时候,我比较推荐w3cschool和菜鸟教程这两个网站。

w3cschool-学编程,从w3cschool开始www.w3cschool.cn!

菜鸟教程 - 学的不仅是技术,更是梦想!www.runoob.com

这两个网站在我看来,是编程自学的福音。

w3cschool这个网站手册非常棒,另外这个网站的编程微课以及编程实战对新手来说非常友好!

我当时就是靠这两个,引发我学习的乐趣,不然对着枯燥的代码,说实话,很无聊的。

菜鸟教程,这个网站的实例是最棒的,很多时候,你不仅仅要自己看教程,还要去看看为什么,而菜鸟教程的实例就能够让你清晰的知道,为什么,并且会原来如此。

总的来说,这两个网站就像新手村刚出来的剑和盾!是新手入门绝对不能少的,尤其是w3cschool,强烈推荐。

还有一个就是视频,视频我是在慕课网上面看的,我很喜欢慕课网这个网站,网站风格很棒,而且视频也很清晰。

也可以在阿里云上面看Python的视频,也很不错,并且是免费的。

进阶

进阶结束后,代表你是个初级工程师。

这一步实践非常重要,你要自己动手,做一些小玩意,实践才是最重要的,在实践中发现问题,那是学习最快并且效率最高的时刻。

你可以先给自己定下一个目标,比如我要做一个简单的页面,或者我要做一个简单的小程序。

然后就开始动手去实践,这步很重要。

同时还是要多看书籍。

进阶pro

到这一步,我建议务必买书,你需要书籍帮你反向梳理你的知识,这决定了你以后的高度,而不是这个也懂,那个也懂,但是东西就是做不出来。

我记得当时我买完书,看完后的第一感受就是:原来这个世界是这样的!

书会非常系统性的帮你梳理你自己学过的知识!

这里只推荐两本书:《Python入门手册》和《Python核心编程》

小伙伴可以自己去亚马逊购买。

然后就是和身边的小伙伴交流!

多看看别人的代码,自己多敲敲代码,是必经之路,也是一定要做的。

以上,希望对想入门Python的小伙伴能够提供一点点帮助。

篇4:Python精选教学心得

1、定义方法

关键字 def 是方法定义的标志。接下来紧跟方法名和被圆括号所包围的参数列表。方法的主

体语句将在下一行开始并且必须缩进。

方法主体的首句可选择性地是一句字符,用来说明方法的主要功能

例如:

“”“print a finabo series up to n.”“”

2、默认参数值

默认值仅被设置一次,这与以前默认值为可变对象(如列表、字典和多数类实

例时)有很大的区别。

例如:

i=5

def f(arg=i):

print(arg)

i=6

f

将会输出 5

3、关键字参数

可以通过形式关键字参数调用方法

在方法调用中,关键字参数必须遵循位置参数。 所有的关键参数必须符合方法接受的参数

其中之一。但是他们的次序不重要,这包含非选择的参数。没有参数可以多次接受一个值。

当最后一个形参是__name 时,它可以接受包含除了形式参数之外的所有关键字的字典,

_name 必须在__name 之前出现

4、可变参数列表

正常来说,这些可变参数常常放在正式参数列表的后面,因为它们会包揽所有传递给该方法

的剩余输入参数。任何出现在_args 参数后低的正式参数会被认为是关键字参数,意味着它

们只能当关键字使用而不是位置参数。

>>>def concat(_args,sep=“/”):

...returnsep.join(args)

...

>>>concat(“earth”,“mars”,“venus”)

’earth/mars/venus’

>>>concat(“earth”,“mars”,“venus”, sep=“.”)

’earth.mars.venus’

5、拆分参数列表

当参数已经存在列表或者元组中,但是需要分拆以供要求分离位置参数调用的方法,如果单独

分开它们无法使用,就需要写一个方法用 _ 操作符来调用实现分拆列表或者元组中的参数。

同样的使用形式,字典可以用__ 操作符实现关键字参数。

6、形式

lamdba a,b:a+b 该函数表示两个数的和,像内嵌函数

7、代码风格

对于 python,PEP8 作为许多项目应该遵守的编码指导书而做的。 它提出了一种可读而悦

目的编码风格。 每位 python 开发者应该读它。这里抽出一个重要的事项与你分享 :

? 用四个空格代替 tab 键

? 每行不要超过 79 个字符。

? 用空行分离方法和类,大块代码中的方法。

? 必要的时候为每行添加注释。

? 用文档字符串

? 在操作符两边用空格

? 用统一的风格命名自定义的方法和类

? 如果你的代码打算用在国际环境中,请不要用想象的字符编码。Python 默认的是

utf-8,在任何情况下可以用 Ascii .

? 同样的,即使有很少机会让说不同语言的人们读代码或者维护代码,但在定义中不

要用非 ASCII 编码字符。

篇5:Python精选教学心得

011月,一群编程零基础的小伙伴们成立了Python学习小组,12名学员从此夜以继日地奔赴学习的征程。一个月过去了,从在屏幕上用最简单的语句打印出“Hello, Python; Hello, World”开始,我们逐步地学习Python语法,学习操作列表、字典,学习For,While,If语句,现在遇到了第一个难点:类。通过研读、练习、交流、讨论,作为程序界的小白,我们逐步地理解了类的概念,明白了面向对象与面向过程编程的差异,以下是我们的小小心得,与大家分享:

编程基本思想

现实世界中,每个复杂的事务都可以拆分为多个组成部分,其中的每一部分就可称之为对象。比如要实现一个很大很复杂的项目,我们可以把项目拆分成不同的组成部分,然后分别对不同部分通过编程实现,最终再把各个部分组装起来完成整个项目。这让我们能够从整体上来控制项目,从而让程序开发更有效。

比如汽车制造,汽车厂所做的仅仅是各个部件的组装和匹配,而各个部件的生产是由相对专业的厂商完成。如果需要研发新型号汽车,整车厂所考虑的是如何对各个新式的零部件进行新的组装和匹配,而不是从头到尾重新生产一辆汽车。

面向对象的编程

VS

面向过程的编程

面向过程编程是针对一个需求的具体实现过程,但是对于大型项目的复杂需求,一步一步的做,这种编程效率显然是低下的。

面向对象编程则是对项目进行拆分后(一般按照功能拆分),分别实现,再将各个对象组装起来。因此简单的小程序使用面向过程方法编程更适合。面向对象的编程特性是易维护(可读性高),效率高,质量高(重用性),扩展性好(高内聚,低耦合)。

对象

通俗的讲,对象就是事物,一个公司、一个部门、一个人,甚至一本书都可以是一个对象,程序员可以自由决定把什么作为对象。

比如eHR系统,需要对组织架构,员工进行管理,所以使用的对象可能是公司,部门,岗位,员工,等等。对象可大可小,可复杂也可简单,如果仅仅是做一个考勤系统,员工这个对象一定要比eHR系统中的员工对象简单。

现实世界中,类代表一组有共同特性的事物,把不同对象之间的共性抽象出来,就形成类的概念。比如说男人、女人可以抽象成人这个类;处长、秘书可以抽象成员工类。至于类如何去抽象,粒度的粗细,这是一个需要在学习和实践中摸索的过程。

实例

以下是一个实例,大家体会一下:

1. 定义父类:

class Employee:

def __init__(self, name, age): #抽象员工共性(名字,年龄)

self.name = name

self.age = age

def signON(self):

print(self.name+“ sign on.”) #抽象签到的动作

def work(self):

print(self.name + “ on work.”) #抽象工作的动作

2. 继承出子类:

class MEmployee(Employee): #继承父类的共性

def __init__(self, name, age):

super().__init__(name, age)

def work(self): #重写子类的方法(抽象出从事管理岗位工作的动作)

print(self.name + “ on manager_work.”)

3. 继承出第二个子类:

class TEmployee(Employee):

def __init__(self, name, age, devLanguage): #继承父类的共性,增加语言的属性

super().__init__(name, age)

self.devLanguage = devLanguage

def work(self): #重写子类的方法(抽象出从事技术岗位工作的动作)

print(self.name + “ on technology_work.”)

def showLanguage(self): #增加子类的方法(抽象出会某种编程语言的动作)

print(“use ”+self.devLanguage+“ language.”)

在上面的程序中,我们先定义了一个父类:包含员工的姓名、年龄等一般特性,可以执行签到、工作这两类动作。在第一个子类中,管理层在前面一般特性的基础上,执行管理工作;在第二个子类中,作为一般员工在前面一般特性的基础上,执行技术工作,从事编程。

篇6:Python常用模块

Python模块

模块是Python最高级别的程序组织单元,他将程序代码和数据封装起来以便重用,

实际来看模块往往对应Python程序文件。本质就是用一些代码实现某些功能的集合

这个集合可以是一个.py文件,也可以是一个包(一个文件夹中,有一个.py入口文件)

一、导入模块

import module

from module.xx import xx

from module.xx import xx as rename

from module.xx import *

导入一个py文件,解释器解释该文件

导入一个包

导入模块根据路径 sys.path如果有该路径,就可直接导入

如果sys.path么有想要的路径,通过sys.path.append('路径')

二、开源模块

下载安装

1、yum、pip、apt-get

2、源码编译安装:Python setup.py build Python setup install

三、常用模块

1、os模块#用作系统级别的工作

os.popen('id').read   # 执行系统命令得到返回结果

os.system()        # 得到返回状态 返回无法截取

os.name          # 返回系统平台 Linux/Unix用户是'posix'

os.getenv()        # 读取环境变量

os.putenv()        # 设置环境变量

os.getcwd()        # 当前工作路径

os.chdir()        # 改变当前工作目录

os.walk('/root/')     # 递归路径

文件处理

mkfifo()/mknod()   # 创建命名管道/创建文件系统节点

remove()/unlink()   # 删除文件

rename()/renames()  # 重命名文件

*stat()        # 返回文件信息

symlink()       # 创建符号链接

utime()        # 更新时间戳

tmpfile()       # 创建并打开('w+b')一个新的临时文件

walk()        # 遍历目录树下的所有文件名

目录/文件夹

chdir()/fchdir()   # 改变当前工作目录/通过一个文件描述符改变当前工作目录

chroot()       # 改变当前进程的根目录

listdir()       # 列出指定目录的文件

getcwd()/getcwdu()  # 返回当前工作目录/功能相同,但返回一个unicode对象

mkdir()/makedirs()  # 创建目录/创建多层目录

rmdir()/removedirs() # 删除目录/删除多层目录

访问/权限

saccess()       # 检验权限模式

chmod()        # 改变权限模式

chown()/lchown()   # 改变owner和groupID功能相同,但不会跟踪链接

umask()        # 设置默认权限模式

文件描述符操作

open()        # 底层的操作系统open(对于稳健,使用标准的内建open()函数)

read()/write()    # 根据文件描述符读取/写入数据 按大小读取文件部分内容

dup()/dup2()     # 复制文件描述符号/功能相同,但是复制到另一个文件描述符

设备号

makedev()       # 从major和minor设备号创建一个原始设备号

major()/minor()    # 从原始设备号获得major/minor设备号

os.path模块

os.path.expanduser('~/.ssh/key') # 家目录下文件的全路径

分隔

os.path.basename()    # 去掉目录路径,返回文件名

os.path.dirname()     # 去掉文件名,返回目录路径

os.path.join()      # 将分离的各部分组合成一个路径名

os.path.spllt()      # 返回(dirname(),basename())元组

os.path.splitdrive()   # 返回(drivename,pathname)元组

os.path.splitext()    # 返回(filename,extension)元组

信息

os.path.getatime()    # 返回最近访问时间

os.path.getctime()    # 返回文件创建时间

os.path.getmtime()    # 返回最近文件修改时间

os.path.getsize()     # 返回文件大小(字节)

查询

os.path.exists()     # 指定路径(文件或目录)是否存在

os.path.isabs()     # 指定路径是否为绝对路径

os.path.isdir()     # 指定路径是否存在且为一个目录

os.path.isfile()     # 指定路径是否存在且为一个文件

os.path.islink()     # 指定路径是否存在且为一个符号链接

os.path.ismount()    # 指定路径是否存在且为一个挂载点

os.path.samefile()    # 两个路径名是否指向同一个文件

2、sys模块#提供解释器相关操作

sys.argv       # 命令行参数List,第一个元素是程序本身路径

sys.exit(2)     # 退出脚本返回状态 会被try截取

sys.exc_info()    # 获取当前正在处理的异常类

sys.version     # 获取Python解释程序的版本信息

sys.maxint      # 最大的Int值 9223372036854775807

sys.maxunicode    # 最大的Unicode值

sys.modules     # 返回系统导入的模块字段,key是模块名,value是模块

sys.path       # 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值

sys.platform     # 返回操作系统平台名称

sys.stdout      # 标准输出

sys.stdin      # 标准输入

sys.stderr      # 错误输出

sys.exec_prefix   # 返回平立的python文件安装的位置

sys.stdin.readline() # 从标准输入读一行

sys.stdout.write(“a”) # 屏幕输出a

3、hashlib模块# 用于加密相关的操作

常规加密

import hashlib

hash_md5 = hashlib.md5()

hash_md5.update('admin')

print(hash_md5.hexdigest())

hash = hashlib.sha512()

hash.update('admin')

print hash.hexdigest()

#以上加密算法虽然依然非常厉害,但时候存在缺陷,即:通过撞库可以反解。所以,有必要对加密算法中添加自定义key再来做加密。

添加自定义key做加密

import hashlib

hash = hashlib.md5('898oaFs09f')

hash.update('admin')

print hash.hexdigest()

超 加密-对我们创建的key和内容继续加密

import hmac

h = hmac.new('wueiqi')

h.update('hellowo')

print h.hexdigest()

4、json和pickle模块 #用于序列化数据

json,#json解决简单数据类型的序列换

pickle,#能存储python的复杂数据类型

Json模块提供了四个功能:dumps、dump、loads、load

pickle模块提供了四个功能:dumps、dump、loads、load

name_tra=json.dumps('[1,2,3,4,5]') #dunmps将序列化的数据放到内存

with open('json_tra','wb') as f_json:

f_json.write(name_tra)

with open('json_tra1','wb') as f_json:#dump直接将内存中序列化的数据写入文件

json.dump(a,f_json)

time_now=datetime.datetime.now()

pickle_mem=p.dumps(time_now)

pickle_load=p.loads(pickle_mem)

5、subprocess模块

subprocess包来fork一个子进程,并运行一个外部的程序,

subprocess包中定义有数个创建子进程的函数。subprocess还提供了一些管理标准流(standard stream)和管道(pipe)的工具,从而在进程间使用文本通信。

subprocess.call()

父进程等待子进程完成

返回退出信息(returncode,相当于Linux exit code)

b=subprocess.call(['ls','-l'])

b=subprocess.call(“ls -l”,shell=True)

shell=True,允许shell命令是字符串形式。

subprocess.check_call()

父进程等待子进程完成

返回0

检查退出信息,如果returncode不为0,则举出错误subprocess.CalledProcessError,该对象包含有returncode属性,可用try…except…来检查

subprocess.check_call([“ls”, “-l”])

subprocess.check_call(“exit 1”, shell=True)

subprocess.check_output()

父进程等待子进程完成

返回子进程向标准输出的输出结果

检查退出信息,如果returncode不为0,则举出错误subprocess.CalledProcessError,该对象包含有returncode属性和output属性,output属性为标准输出的输出结果,可用try…except…来检查

6、shuit模块 #文件的复制移动

shutil.copyfile('data.db', 'archive.db')      # 拷贝文件

shutil.move('/build/executables', 'installdir')   # 移动文件或目录

7、logging模块#格式化记录日志

#通过logging.basicConfig函数对日志的输出格式及方式做相关配置,日志将被写入文件

logging.basicConfig(level=logging.DEBUG,

format='%(asctime)s [line:%(lineno)d] %(levelname)s %(message)s',

datefmt='%Y/%m/%d %H:%M:%S',

filename='myapp.log',

filemode='a')

logging.debug('This is debug message')

logging.info('This is info message')

logging.warning('This is warning message')

#logging.basicConfig函数各参数:

#datefmt: 指定时间格式,同time.strftime()

#filename: 指定日志文件名

#filemode: 和file函数意义相同,指定日志文件的打开模式,'w'或'a'

#level: 设置日志级别,默认为logging.WARNING

#format: 指定输出的格式和内容,format可以输出很多有用信息,如上例所示:

# %(asctime)s: 打印日志的时间

# %(levelname)s: 打印日志级别名称

# %(message)s: 打印日志信息

# %(levelno)s: 打印日志级别的数值

# %(lineno)d: 打印日志的当前行号

# %(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0]

# %(filename)s: 打印当前执行程序名

# %(funcName)s: 打印日志的当前函数

# %(thread)d: 打印线程ID

# %(threadName)s: 打印线程名称

# %(process)d: 打印进程ID

#将日志同时写入文件,并打印到屏幕

logging.basicConfig(level=logging.DEBUG,

format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',

datefmt='%Y/%m%d %H:%M:%S',

filename='myapp.log',

filemode='w')

#打印到屏幕

console = logging.StreamHandler()

console.setLevel(logging.WARNING)

formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')

console.setFormatter(formatter)

logging.getLogger().addHandler(console)

8、random模块 用于取随机数

random.choice(['apple', 'pear', 'banana']) # 随机取列表一个参数

random.sample(xrange(100), 10) # 不重复抽取10个

random.randrange(3,7) #随机抽取整数范围不包括7

random.random()        # 随机浮点数

9、time datetime模块时间模块

时间戳 #1970年1月1日之后的秒,即:time.time()

格式化的字符串 # -11-11 11:11,  即:time.strftime('%Y-%m-%d')

结构化时间 # 元组包含了:年、日、星期等... time.struct_time  即:time.localtime()

import time

time.time()             # 时间戳[浮点]

time.localtime()[1] - 1       # 上个月

int(time.time())          # 时间戳[整s]

time.strftime('%Y-%m-%d %X') #格式化输出时间

import datetime

datetime.datetime.datetime.now() #现在的时间

datetime.datetime.now() - datetime.timedelta(days=5,hours=3,seconds=3,minutes=2) #减时间

10、re模块 正则匹配

#Pattern对象是一个编译好的正则表达式,通过Pattern提供的一系列方法可以对文本进行匹配查找。

pattern=re.compile(strPattern[, flag]):

flag是匹配模式,re.I|re.M表示同时生效。

re.I(re.IGNORECASE): 忽略大小写

M(MULTILINE): 多行模式,改变'^'和'$'的行为

match(string[, pos[, endpos]]) | re.match(pattern, string[, flags]): #结果匹配一次

#match(string[, pos[, endpos]])从string的pos下标处起尝试匹配pattern;如果pattern结束时仍可匹配,则返回一个Match对象;

pos和endpos的默认值分别为0和len(string);re.match()flags用于编译pattern时指定匹配模式。

#re.match(pattern, string[, flags])不能指定pos和endpos值。所以匹配的是在开头进行匹配。

search(string[, pos[, endpos]]) | re.search(pattern, string[, flags]): #结果匹配一次

#search(string[, pos[, endpos]])从string的pos下标处起尝试匹配pattern,如果pattern结束时仍可匹配,则返回一个Match对象;

若无法匹配,则将pos加1后重新尝试匹配;直到pos=endpos时仍无法匹配则返回None。

#re.search(pattern, string[, flags]) ,用于匹配任意开始位

a='321.423.432.432 33.43.5.42 1.2.443.34 255.52.53.255 2.2.2.2 3.3.3.3'

pattern=re.compile(r'([12]?\d{1,2}\.){3}([12]?\d{1,2})')

print pattern.search(a).group()

split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]):

按照能够匹配的子串将string分割后返回列表。maxsplit用于指定最大分割次数,不指定将全部分割。

#a='qwe123dsa43** ***2*342rew'

#print re.split('[\d* ]+',a)

findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]):

搜索string,以列表形式返回全部能匹配的子串。

p = re.compile(r'\d+')

print p.findall('one1two2three3four4')

sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]):

使用repl替换string中每一个匹配的子串后返回替换后的字符串。

count用于指定最多替换次数,不指定时全部替换。

a='321.423.432.432 33.43.5.42 1.2.443.34 255.52.53.255 2.2.2.2 3.3.3.3'

pattern=re.compile(r'([12]?\d{1,2}\.){3}([12]?\d{1,2})')

print pattern.sub('bibi',a)

finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]):

搜索string,返回一个顺序访问每一个匹配结果(Match对象)的迭代器。

a='321.423.432.432 33.43.5.42 1.2.443.34 255.52.53.255 2.2.2.2 3.3.3.3'

pattern=re.compile(r'([12]?\d{1,2}\.){3}([12]?\d{1,2})')

for i in pattern.finditer(a):

print(i.group())

篇7:Python 类型

python是动态类型语言,不需要预先声明变量的类型,变量类型和值在赋值的那一刻被初始化

python使用对象模型来存储数据,构造任何类型的值都是一个对象

数字(Number)

有符号整型

长整型

布尔值

浮点数

负数

decimal(2.4版新增)用于十进制浮点型,但需要引入包decimal

>>>import decimal

>>>print decimal.Decimal(1.1)

1.100000000000000088817841970012523233890533447265625

python 2.3开始,超出整型范围的会自动转换为长整型,

字符串(String)

单引号与双引号等价,三引号保留原字符串格式,'+'用于字符串连接,'*'用于字符串重复

[]:索引操作符,[:]:切片操作符

复制代码

>>>pystr = “python”

>>>pystr[0]

'p'

>>>pystr[2:4]

'th'

>>>pystr + ' cool'

'python cool'

>>>pystr * 2

'pythonpython'

复制代码

列表(list)

列表用[ ]标识。是python最通用的复合数据类型

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]

列表解析:在一行中使用for循环,将所有值放到一个列表中

>>>pylist = [x ** 2 for x in range(4)]

>>>type(pylist)

>>>print pylist

[0, 1, 4, 9]

对于上述的列表解析形式,有一种很类似的形式使用的操作时,但返回的是迭代器(generator)类型,在此列出加以区分(注意不要与元组混淆)

>>>pya = (x ** 2 for x in range(4))

>>>type(pya)

>>>for i in pya:

print i

列表同样满足索引操作([]),切片操作([:])

元组(Tuple)

元组用“()”标识,

内部元素用逗号隔开。但是元素不能二次赋值,相当于只读列表。

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )

元组同样满足索引操作([]),切片操作([:])

字典(dictionary)

字典是python中的映射数据类型,类似于perl中的关联数组或哈希表,由键-值(key-value)对构成,一般用不可变对象(immutable)作为键值

字典用“{ }”标识。字典由索引(key)和它对应的值value组成。

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

字典(dictionary)是除列表外python之中最灵活的内置数据结构类型。两者之间的区别在于(当然不止以下区别):

列表是有序的对象结合,字典是无序的对象集合。

字典当中的元素是通过键来存取的,而列表通过偏移存取。

集合(set)

集合对象是一组无序排列的可哈希值,因此集合成员可以作为字典的键。

因集合是无序的,故无法对集合执行索引和切片操作。

集合分为可变集合(set)和不可变集合(frozenset);对可变集合可以执行简单的添加和删除等操作。

复制代码

>>># 集合set的简单操作

>>>s = set('python')     # 利用工厂函数set()创建集合

>>>s

set(['h', 'o', 'n', 'p', 't', 'y'])

>>>'p' in s       # 判断元素是否在集合中

True

>>>set('py') < s       # 子集

True

复制代码

可以看到上面,集合的打印结果是无序的,而且以上只是简单举例集合操作,想要了解更多关于集合的操作可以使用函数dir() 和help()查看。

可变对象(mutable)和不可变对象(immutable)的区别

首先再次声明,在python中所有的类型操作都作为对象处理,而且对变量的使用不需要预先声明类型(其实这里不该使用“变量”描述,姑且用“变量”代替吧),python会根据变量的值动态确定变量类型并存储在内存中(这是python的一大特点),对于immutable类型,若要改变它的值,采取的机制是分配一个新的对象(这里不必担心内存浪费的情况,python有自己的一套内存回收机制);而对于mutable 类型还是在原来的内存地址上进行操作,~~类似于在C++ 中的引用。

篇8:python zipfile模块

#!/usr/bin/env pythonimport zipfileimport os# create a compress file for /etcz = zipfile.ZipFile('/root/etc.zip', 'w')for root, dirs, files in os.walk('/etc'): for file in files: z.write(os.path.join(root, file))z.close# check the name list of the compressed file 'etc.zip'z = zipfile.ZipFile('/root/etc.zip')for name in z.namelist(): print namez.close()# viewing compressed information via 'zipinfo object'z = zipfile.ZipFile('/root/etc.zip')for i in z.infolist(): print i.filename, i.date_time, i.compress_typez.close()# extractall files to /tmp directoryz = zipfile.ZipFile('/root/etc.zip')z.extractall(path='/tmp')z.close()

篇9:Python模块Modules

If you quit from the Python interpreter and enter it again, the definitions you have made (functions and variables) are lost. Therefore, if you want to write a somewhat longer program, you are better off using a text editor to prepare the input for the interpreter and running it with that file as input instead. This is known as creating a script. As your program gets longer, you may want to split it into several files for easier maintenance. You may also want to use a handy function that you’ve written in several programs without copying its definition into each program.

如果你关闭Python解释器(IDLE),然后再打开,那么以前变量的定义则会丢失,因此,如果你想要写长一点的程序,最好先在编辑器中编写Python程序,然后将文件作为输入导入到IDLE解释执行。这就是所谓的创建一个脚本。当你的程序变得越来越大,你可能想要将程序分开到几个文件中。你可能想要写一个便利的函数,能够在几个程序中重复利用。

To support this, Python has a way to put definitions in a file and use them in a script. or in an interactive instance of the interpreter. Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script. executed at the top level and in calculator mode).

为了支持这种功能,Python可以把代码用文件存储,并作为一个脚本,或用来与解释器交互。这种文件就叫做模块。模块中定义可以被导出到另一个模块中或导入到main模块中。

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Within a module, the module’s name (as a string) is available as the value of the global variable __name__. For instance, use your favorite text editor to create a file called fibo.py in the current directory with the following contents:

一个模块就是一个文件,这个模块包含了Python的定义和语句。文件的名字就是模块的名字加后缀.py。在模块内部,该模块的名字可以使用全局变量__name来表示。例如,使用你最喜欢的文本编辑器创建一个文件fibo.py,文件内容如下:

复制代码

# Fibonacci numbers module

def fib(n):  # write Fibonacci series up to n

a, b = 0, 1

while b < n:

print(b, end=' ')

a, b = b, a+b

print()

def fib2(n): # return Fibonacci series up to n

result = []

a, b = 0, 1

while b < n:

result.append(b)

a, b = b, a+b

return result

复制代码

Now enter the Python interpreter and import this module with the following command:

打开Python IDLE,用下面的命令导入模块(一般Python是通过sys.path指定的路径搜索模块):

>>>import fibo

This does not enter the names of the functions defined in fibo directly in the current symbol table; it only enters the module name fibo there. Using the module name you can access the functions:

这个导入命令,不会将该模块的所有函数的名字自己导入到当前的符号表中,它仅仅只是将模块的名字导入到当前的符号表中,使用模块的名字,你可以访问它的函数:

>>>fibo.fib(1000)

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

>>>fibo.fib2(100)

[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

>>>fibo.__name__

'fibo'

If you intend to use a function often you can assign it to a local name:

你也可以将函数赋给本地变量:

>>>fib = fibo.fib

>>>fib(500)

1 1 2 3 5 8 13 21 34 55 89 144 233 377

6.1. More on Modules

A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. They are executed only the first time the module name is encountered in an import statement. [1] (They are also run if the file is executed as a script.)

模块包含可执行语句和函数定义。这些语句用于初始化模块,他们仅仅在模块第一次导入时被执行。

Each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module. Thus, the author of a module can use global variables in the module without worrying about accidental clashes with a user’s global variables. On the other hand, if you know what you are doing you can touch a module’s global variables with the same notation used to refer to its functions, modname.itemname.

每一个模块有它自己的符号表,这个符号表可以当作是存储模块中所有函数定义的全局符号表。因此,模块的拥有者可以在模块中使用全局变量而不用担心和另一个用户的全局变量引发冲突。另一方面,如果你很清楚你的意图,你可以访问模块的函数,请使用modname.itemname

Modules can import other modules. It is customary but not required to place all import statements at the beginning of a module (or script, for that matter). The imported module names are placed in the importing module’s global symbol table.

模块能够导入其他模块。一种约定俗成的做法是:将所有import语句放在模块的开头。被导入的模块名字会被放置在当前模块的全局符号表中。

There is a variant of the import statement that imports names from a module directly into the importing module’s symbol table. For example:

这里列举了几种不同形式的import语句,从一个模块中直接导入函数到当前模块的符号表中:

>>>from fibo import fib, fib2

>>>fib(500)

1 1 2 3 5 8 13 21 34 55 89 144 233 377

This does not introduce the module name from which the imports are taken in the local symbol table (so in the example, fibo is not defined).

这种导入方式不会将模块名字fibo放入到当前模块的符号表中(例如,输入fibo是未定义的)。

There is even a variant to import all names that a module defines:

这是另一种导入形式:导入所有在模块中定义的名字:

>>>from fibo import *

>>>fib(500)

1 1 2 3 5 8 13 21 34 55 89 144 233 377

This imports all names except those beginning with an underscore (_). In most cases Python programmers do not use this facility since it introduces an unknown set of names into the interpreter, possibly hiding some things you have already defined.

这种导入方式会将所有的名字导入到当前模块的符号表中,除开那些以下划线_开头的变量。在大部分情况下,Python程序员是不会使用这种导入方式的。因为这样会使你导入一些你未知的一些名字到解释器中,可能就会覆盖已经定义的变量。

Note that in general the practice of importing * from a module or package is frowned upon, since it often causes poorly readable code. However, it is okay to use it to save typing in interactive sessions.

注意,一般使用import * 是不被赞成的,因为它的可读性很差。然而,在解释器中为了节省输入,这种形式的导入也是OK的。仅此而已。

6.1.1. Executing modules as scripts

When you run a Python module with

当你这样运行Python模块:

python fibo.py

the code in the module will be executed, just as if you imported it, but with the __name__ set to “__main__”. That means that by adding this code at the end of your module:

当你输入上面的语句时,fibo模块将会被执行,前提是__name__必须设为“__main__”。这就意味着你必须在fibo模块最后面加入下面的代码:

if __name__ == “__main__”:

import sys

fib(int(sys.argv[1]))

you can make the file usable as a script. as well as an importable module, because the code that parses the command line only runs if the module is executed as the “main” file:

你不但可以把它当脚本使用,还可以称为可导入的模块,因为分析命令行的代码仅仅当模块的文件名为main.py时才会被执行。

If the module is imported, the code is not run:

如果导入模块,代码不会运行:

>>>import fibo

>>>

6.1.2. The Module Search Path

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

当模块spam被导入后,解释器首先在内置的模块中寻找该模块的名字。如果没找到,就会在变量sys.path指定的路径中寻找文件名为spam.py的文件。sys.path初始化的路径包括:

The directory containing the input script. (or the current directory when no file is specified).

当前程序所在目录

PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).

PYTHONPATH(一个目录列表,这个变量就是系统环境变量)

The installation-dependent default.

Python默认安装目录。

After initialization, Python programs can modify sys.path. The directory containing the script. being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended. See section Standard Modules for more information.

当sys.path初始化后,Python程序可以修改sys.path的路径。当前正在运行的脚本所在的目录放置在搜索路径的最开头,也就是标准库模块路径的前面。这就意味着如果当前模块的名字和标准库模块的名字相同时,则会替换掉该标准库模块。如果你不是有意要替换该标准库模块,那么可能就会出现错误。

6.1.3. “Compiled” Python files

To speed up loading modules, Python caches the compiled version of each module in the __pycache__ directory under the name module.version.pyc, where the version encodes the format of the compiled file; it generally contains the Python version number. For example, in CPython release 3.3 the compiled version of spam.py would be cached as __pycache__/spam.cpython-33.pyc. This naming convention allows compiled modules from different releases and different versions of Python to coexist.

为了加速加载模块。Python缓存了已经编译好的每个模块的版本,并放置在__pycache__目录下。编译好的模块的名字为:module.version.pyc(module为对应的模块名,version为Python对应的版本)。例如:在CPython release 3.3版本上编译spam.py将会缓存__pycache__/spam.cpython-33.pyc。这种缓存的命名风格允许不同的Python版本共存。

Python checks the modification date of the source against the compiled version to see if it’s out of date and needs to be recompiled. This is a completely automatic process. Also, the compiled modules are platform-independent, so the same library can be shared among systems with different architectures.

针对编译的版本,Python检查源码的修改时间判断该版本是否过期或者需要重新编译。这完全是一个自动完成的过程。同样,编译的模块也是平立的,因此同样的库可以在不同架构的系统上运行。

Python does not check the cache in two circumstances. First, it always recompiles and does not store the result for the module that’s loaded directly from the command line. Second, it does not check the cache if there is no source module. To support a non-source (compiled only) distribution, the compiled module must be in the source directory, and there must not be a source module.

Python在两种情况下不会检查缓存。第一,如果模块执行从命令行加载,则该模块会被重新编译,并且不会保存结果。第二,如果没有源码的模块,将不会检查缓存。为了支持只有编译版本的模块,必须将该模块放置在源码模块目录下,并且不能有该模块的源码。

Some tips for experts:

You can use the -O or -OO switches on the Python command to reduce the size of a compiled module. The -O switch removes assert statements, the -OO switch removes both assert statements and __doc__ strings. Since some programs may rely on having these available, you should only use this option if you know what you’re doing. “Optimized” modules have a .pyo rather than a .pyc suffix and are usually smaller. Future releases may change the effects of optimization.

A program doesn’t run any faster when it is read from a .pyc or .pyo file than when it is read from a .py file; the only thing that’s faster about .pyc or .pyo files is the speed with which they are loaded.

The module compileall can create .pyc files (or .pyo files when -O is used) for all modules in a directory.

There is more detail on this process, including a flow chart of the decisions, in PEP 3147.

6.2. Standard Modules

Python comes with a library of standard modules, described in a separate document, the Python Library Reference (“Library Reference” hereafter). Some modules are built into the interpreter; these provide access to operations that are not part of the core of the language but are nevertheless built in, either for efficiency or to provide access to operating system primitives such as system calls. The set of such modules is a configuration option which also depends on the underlying platform. For example, the winreg module is only provided on Windows systems. One particular module deserves some attention: sys, which is built into every Python interpreter. The variables sys.ps1 and sys.ps2 define the strings used as primary and secondary prompts:

Python有一个标准模块库,该库的说明在另一个单独的文档中,叫做Python库参考。有些模块是解释器内置的(意味着不需要使用import语句);虽然这些内置的模块提供了操作权限(例如访问系统调用),但却不是语言核心的一部分。这些模块是可以通过配置来选择的,并且依赖于不同的平台。例如:winreg模块仅仅在Windows系统中使用。另一个特殊的模块sys值得引起注意,它内置于每一个Python解释器中。变量sys.ps1和sys.ps2定义了两个提示符字符串:

复制代码

>>>import sys

>>>sys.ps1

'>>>'

>>>sys.ps2

'... '

>>>sys.ps1 = 'C>'

C>print('Yuck!')

Yuck!

C>

复制代码

These two variables are only defined if the interpreter is in interactive mode.

这两个变量仅仅是在解释器在交互模式的环境中才被定义。

The variable sys.path is a list of strings that determines the interpreter’s search path for modules. It is initialized to a default path taken from the environment variable PYTHONPATH, or from a built-in default if PYTHONPATH is not set. You can modify it using standard list operations:

变量sys.path包含一个字符串的列表,它觉得了解释器寻找模块的搜索路径。环境变量PYTHONPATH的路径作为它初始化的一部分,如果没有设置PYTHONPATH环境变量,则使用默认的内置路径。你可以标准的列表操作来修改它:

>>>import sys

>>>sys.path.append('/ufs/guido/lib/python')

6.3. The dir() Function

The built-in function dir() is used to find out which names a module defines. It returns a sorted list of strings:

内置的函数dir()常被用来寻找那些已经被模块定义了的变量名字,它返回一个已经排序好了的字符串:

复制代码

>>>import fibo, sys

>>>dir(fibo)

['__name__', 'fib', 'fib2']

>>>dir(sys)

['__displayhook__', '__doc__', '__excepthook__', '__loader__', '__name__',

'__package__', '__stderr__', '__stdin__', '__stdout__',

'_clear_type_cache', '_current_frames', '_debugmallocstats', '_getframe',

'_home', '_mercurial', '_xoptions', 'abiflags', 'api_version', 'argv',

'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder',

'call_tracing', 'callstats', 'copyright', 'displayhook',

'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix',

'executable', 'exit', 'flags', 'float_info', 'float_repr_style',

'getcheckinterval', 'getdefaultencoding', 'getdlopenflags',

'getfilesystemencoding', 'getobjects', 'getprofile', 'getrecursionlimit',

'getrefcount', 'getsizeof', 'getswitchinterval', 'gettotalrefcount',

'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info',

'intern', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path',

'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1',

'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit',

'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout',

'thread_info', 'version', 'version_info', 'warnoptions']

复制代码

Without arguments, dir() lists the names you have defined currently:

如果不输入参数,dir()函数将会列出当前已经定义的名字:

>>>a = [1, 2, 3, 4, 5]

>>>import fibo

>>>fib = fibo.fib

>>>dir()

['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys']

Note that it lists all types of names: variables, modules, functions, etc.

注意:它会列出所有的名字:变量,模块,函数等等,

dir() does not list the names of built-in functions and variables. If you want a list of those, they are defined in the standard module builtins:

dir()不会雷锤内置的函数名和变量名。如果你想要列出这些名字,他们被定义在标准模块builtins中:

复制代码

>>>import builtins

>>>dir(builtins)

['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',

'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',

'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError',

'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning',

'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',

'FileExistsError', 'FileNotFoundError', 'FloatingPointError',

'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError',

'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError',

'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError',

'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented',

'NotImplementedError', 'OSError', 'OverflowError',

'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError',

'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning',

'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError',

'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError',

'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',

'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning',

'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__',

'__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs',

'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable',

'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits',

'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit',

'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr',

'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass',

'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview',

'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property',

'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',

'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars',

'zip']

复制代码

6.4. Packages

Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A. Just like the use of modules saves the authors of different modules from having to worry about each other’s global variable names, the use of dotted module names saves the authors of multi-module packages like NumPy or the Python Imaging Library from having to worry about each other’s module names.

包是一种构建Python模块命名空间的方式,通过使用“packagename.modulename”。例如,模块名:A.B 说明子模块B在包A中。

Suppose you want to design a collection of modules (a “package”) for the uniform. handling of sound files and sound data. There are many different sound file formats (usually recognized by their extension, for example: .wav, .aiff, .au), so you may need to create and maintain a growing collection of modules for the conversion between the various file formats. There are also many different operations you might want to perform. on sound data (such as mixing, adding echo, applying an equalizer function, creating an artificial stereo effect), so in addition you will be writing a never-ending stream of modules to perform. these operations. Here’s a possible structure for your package (expressed in terms of a hierarchical filesystem):

假设你希望设计一个模块的集合(也就是设计一个包)来统一处理音频文件和音频数据。这里有许多不同的音频格式(通常可以通过后缀来识别,例如.wav,.aiff,.au),因此你可能需要创建和维护增加的模块来处理不同的文件格式之间的转换。同样,你可能也想要在处理音频数据上执行多种操作,因此,你将会写一个无尽的流模块来处理这些操作。这里有一个包的设计架构可能是你需要的:

复制代码

sound/             Top-level package

__init__.py       Initialize the sound package

formats/         Subpackage for file format conversions

__init__.py

wavread.py

wavwrite.py

aiffread.py

aiffwrite.py

auread.py

auwrite.py

...

effects/         Subpackage for sound effects

__init__.py

echo.py

surround.py

reverse.py

...

filters/         Subpackage for filters

__init__.py

equalizer.py

vocoder.py

karaoke.py

...

复制代码

When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.

当你导入包的时候,Python将通过sys.path指定的路径来寻找包的子目录。

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

__init__.py文件是必须要存在的,这样Python才会将目录看作是包; 如果你使用一个普遍的名字命名包,例如string,如果后面有string模块,则会使该模块失效。最简单的情况是,__init__.py是一个空文件,但是它也可以包含包的初始化代码或者设置变量__all__的值,下面将会更详细的表述。

Users of the package can import individual modules from the package, for example:

包的使用者,可以从包中导入单个模块,例如:

import sound.effects.echo

This loads the submodule sound.effects.echo. It must be referenced with its full name.

加载子模块sound.effects.echo.调用时必须使用全名称:

sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)

An alternative way of importing the submodule is:

另一种替代方式是:

from sound.effects import echo

This also loads the submodule echo, and makes it available without its package prefix, so it can be used as follows:

这也是加载子模块echo,调用时不需要加包的前缀,因此可以这样使用:

echo.echofilter(input, output, delay=0.7, atten=4)

Yet another variation is to import the desired function or variable directly:

还有一种方式是直接导入想调用的函数:

from sound.effects.echo import echofilter

Again, this loads the submodule echo, but this makes its function echofilter() directly available:

同样,加载子模块echo,但是可以直接使用函数echofilter():

echofilter(input, output, delay=0.7, atten=4)

Note that when using from package import item, the item can be either a submodule (or subpackage) of the package, or some other name defined in the package, like a function, class or variable. The import statement first tests whether the item is defined in the package; if not, it assumes it is a module and attempts to load it. If it fails to find it, an ImportError exception is raised.

注意,当使用语句from package import item,这个item可以是子模块(或子包)也可以是包里面定义的对象,比如函数,类或者变量。import语句首先检查item是否在包中已经定义,如果没有,它就认为这是一个模块,并尝试加载它,如果加载失败,则抛出ImportError异常。

Contrarily, when using syntax like import item.subitem.subsubitem, each item except for the last must be a package; the last item can be a module or a package but can’t be a class or function or variable defined in the previous item.

相反,当使用语句import item.subitem.subsubitem时,除开最后一个subsubitem,其他都必须是包;最后一个subsubitem可以是模块,也可以是包,但不能是类或者函数、变量。

6.4.1. Importing * From a Package

Now what happens when the user writes from sound.effects import *? Ideally, one would hope that this somehow goes out to the filesystem, finds which submodules are present in the package, and imports them all. This could take a long time and importing sub-modules might have unwanted side-effects that should only happen when the sub-module is explicitly imported.

当用户使用from sound.effects import*时,则所有的模块都被导入,这将会花费很长的时间,并且可能产生意想不到的负面效果。

The only solution is for the package author to provide an explicit index of the package. The import statement uses the following convention: if a package’s __init__.py code defines a list named __all__, it is taken to be the list of module names that should be imported when from package import * is encountered. It is up to the package author to keep this list up-to-date when a new version of the package is released. Package authors may also decide not to support it, if they don’t see a use for importing * from their package. For example, the file sound/effects/__init__.py could contain the following code:

唯一的解决办法就是包的作者提供一个显式的包的索引。import语句使用下面的惯例:如果一个包的__init__.py文件定义了变量__all__时,当使用语句from package import*,则会导入__all__变量所定义列表中的值。当有新版本的包要发布时,应该由作者保持对该列表的更新。当作者不想看到用户使用import *语句时,包的作者也可以决定不使用它。例如,文件sound/effects/__init__.py包含下面的代码:

__all__ = [“echo”, “surround”, “reverse”]

This would mean that from sound.effects import * would import the three named submodules of the sound package.

这就意味着from sound.effects import *将会导入effects包的三个子模块。

If __all__ is not defined, the statement from sound.effects import * does not import all submodules from the package sound.effects into the current namespace; it only ensures that the package sound.effects has been imported (possibly running any initialization code in __init__.py) and then imports whatever names are defined in the package. This includes any names defined (and submodules explicitly loaded) by __init__.py. It also includes any submodules of the package that were explicitly loaded by previous import statements. Consider this code:

如果没有定义变量__all__,语句from sound.effects import*将不会把effect包的子模块导入到当前的命名空间中;它仅仅只确保包sound.effects被导入,然后再导入在effects包中定义的变量名。这包含任何在__init__.py文件中定义的变量名。考虑下面的代码:

import sound.effects.echo

import sound.effects.surround

from sound.effects import *

In this example, the echo and surround modules are imported in the current namespace because they are defined in the sound.effects package when the from...import statement is executed. (This also works when __all__ is defined.)

在这个例子中,模块echo和surround被导入到当前的命名空间中,因为当from...import语句被执行时,他们就被定义在sound.effects包里面。

Although certain modules are designed to export only names that follow certain patterns when you use import *, it is still considered bad practise in production code.

尽管某些模块只是用来导出变量名,但import *始终被认为是一种不好的导入方式。

Remember, there is nothing wrong with using from Package import specific_submodule! In fact, this is the recommended notation unless the importing module needs to use submodules with the same name from different packages.

记住,使用from Package import specific_submodule是不会错的!实际上,这也是被建议的一种方式,

6.4.2. Intra-package References

When packages are structured into subpackages (as with the sound package in the example), you can use absolute imports to refer to submodules of siblings packages. For example, if the module sound.filters.vocoder needs to use the echo module in the sound.effects package, it can use from sound.effects import echo.

当一个包有子包时(例如包sound),你可以使用绝对路径引用包同级的子模块。例如,如果模块sound.filters.vecoder需要使用sound.effects包中echo模块,可以使用语句:from sound.effects import echo。

You can also write relative imports, with the from module import name form. of import statement. These imports use leading dots to indicate the current and parent packages involved in the relative import. From the surround module for example, you might use:

你也能够用相对路径导入通过 rom module import name形式的导入语句。这些导入语句需要使用 . 来表示当前或父包。例如当在surround模块中使用下面的其他子模块时,你可以使用:

from . import echo

from .. import formats

from ..filters import equalizer

Note that relative imports are based on the name of the current module. Since the name of the main module is always “__main__”, modules intended for use as the main module of a Python application must always use absolute imports.

注意,相对路径的导入是基于当前模块的。因为main模块的名字总是“__main__”,如果模块打算当作Python应用程序的主模块使用时,必须总是使用绝对路径。

6.4.3. Packages in Multiple Directories

Packages support one more special attribute, __path__. This is initialized to be a list containing the name of the directory holding the package’s __init__.py before the code in that file is executed. This variable can be modified; doing so affects future searches for modules and subpackages contained in the package.

包还支持其他特殊的属性,例如__path__。这个变量定义了一个列表,该列表包含了包的__init.__py所在的目录路径。这个变量能被修改。这将影响包中对子包和子模块的搜索。

While this feature is not often needed, it can be used to extend the set of modules found in a package.

然而这种特性不是常需要的,它能够用来扩展包中子模块的搜索路径。

篇10:Python struct.unpack

-11-11Python GAE、Django导出Excel的方法

-06-06python 实现归并排序算法

-05-05Python Web开发模板引擎优缺点总结

2012-08-08python 实现文件的递归拷贝实现代码

-03-03python用ConfigObj读写配置文件的实现代码

-04-04Python 自动安装 Rising 杀毒软件

2014-05-05Python中os和shutil模块实用方法集锦

2014-06-06Python和Ruby中each循环引用变量问题(一个隐秘BUG?)

2014-01-01使用cx_freeze把python打包exe示例

2013-11-11详细介绍Python语言中的按位运算符

篇11:Python struct.unpack

最近更 新

python实现数通设备tftp备份配置文件示例

使用python统计文件行数示例分享

通过python下载FTP上的文件夹的实现代码

videocapture库制作python视频高速传输程

Python BeautifulSoup中文乱码问题的2种解

python定时器使用示例分享

python类定义的讲解

Python使用urllib2获取网络资源实例讲解

python批量下载图片的三种方法

Python 初始化多维数组代码

热 点 排 行

Python入门教程 超详细1小时学会

python 中文乱码问题深入分析

比较详细Python正则表达式操作指

Python字符串的encode与decode研

Python open读写文件实现脚本

Python enumerate遍历数组示例应

Python 深入理解yield

Python+Django在windows下的开发

python 文件和路径操作函数小结

python 字符串split的用法分享

篇12:Python 元组

元组可以使用下标索引来访问元组中的值,如下实例:

#!/usr/bin/pythontup1 = ('physics', 'chemistry', , );tup2 = (1, 2, 3, 4, 5, 6, 7 );print “tup1[0]: ”, tup1[0]print “tup2[1:5]: ”, tup2[1:5]

以上实例输出结果:

tup1[0]: physicstup2[1:5]: (2, 3, 4, 5)

篇13:Python 元组

元组中的元素值是不允许修改的,但我们可以对元组进行连接组合,如下实例:

#!/usr/bin/python# -*- coding: UTF-8 -*-tup1 = (12, 34.56);tup2 = ('abc', 'xyz');# 以下修改元组元素操作是非法的。# tup1[0] = 100;# 创建一个新的元组tup3 = tup1 + tup2;print tup3;

以上实例输出结果:

(12, 34.56, 'abc', 'xyz')

篇14:Python 元组

元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组,如下实例:

#!/usr/bin/pythontup = ('physics', 'chemistry', , );print tup;del tup;print “After deleting tup : ”print tup;

以上实例元组被删除后,输出变量会有异常信息,输出如下所示:

('physics', 'chemistry', 1997, 2000)After deleting tup :Traceback (most recent call last): File “test.py”, line 9, inprint tup;NameError: name 'tup' is not defined

篇15:Python 元组

与字符串一样,元组之间可以使用 + 号和 * 号进行运算,

这就意味着他们可以组合和复制,运算后会生成一个新的元组。

Python 表达式结果描述len((1, 2, 3))3计算元素个数(1, 2, 3) + (4, 5, 6)(1, 2, 3, 4, 5, 6)连接['Hi!'] * 4['Hi!', 'Hi!', 'Hi!', 'Hi!']复制3 in (1, 2, 3)True元素是否存在for x in (1, 2, 3): print x,1 2 3迭代

篇16:Python 元组

因为元组也是一个序列,所以我们可以访问元组中的指定位置的元素,也可以截取索引中的一段元素,如下所示:

元组:

L = ('spam', 'Spam', 'SPAM!')Python 表达式结果描述L[2]'SPAM!'读取第三个元素L[-2]'Spam'反向读取;读取倒数第二个元素L[1:]('Spam', 'SPAM!')截取元素

Python continue 语句

Python入门简单操作

教学设计

设计教学

教学设计

python课程实训心得体会

python单元测试unittest实例详解

Python数据结构与算法算法分析

教学设计点评

曹冲称象教学设计

python教学设计(锦集16篇)

欢迎下载DOC格式的python教学设计,但愿能给您带来参考作用!
推荐度: 推荐 推荐 推荐 推荐 推荐
点击下载文档 文档为doc格式

猜你喜欢

NEW
点击下载本文文档