十、Python标准库

  Python标准库是随Pthon附带安装的,包含了大量极其有用的模块。

  1. sys模块  sys模块包含系统对应的功能

  • sys.argv  ---包含命令行参数,第一个参数是py的文件名
  • sys.platform  ---返回平台类型
  • sys.exit([status])  ---退出程序,可选的status(范围:0-127):0表示正常退出,其他表示不正常,可抛异常事件供捕获
  • sys.path    ---程序中导入模块对应的文件必须放在sys.path包含的目录中,使用sys.path.append添加自己的模块路径
  • sys.modules  ---This is a dictionary that maps module names to modules which have already been loaded
  • sys.stdin,sys.stdout,sys.stderr  ---包含与标准I/O 流对应的流对象
s = sys.stdin.readline()

sys.stdout.write(s)

  2. os模块  该模块包含普遍的操作系统功能

  • os.name字符串指示你正在使用的平台。比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'
  • os.getcwd()函数得到当前工作目录,即当前Python脚本工作的目录路径
  • os.getenv()和os.putenv()函数分别用来读取和设置环境变量
  • os.listdir()返回指定目录下的所有文件和目录名
  • os.remove()函数用来删除一个文件
  • os.system()函数用来运行shell命令
  • os.linesep字符串给出当前平台使用的行终止符。例如,Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'
  • os.sep 操作系统特定的路径分割符
  • os.path.split()函数返回一个路径的目录名和文件名
  • os.path.isfile()和os.path.isdir()函数分别检验给出的路径是一个文件还是目录
  • os.path.existe()函数用来检验给出的路径是否真地存在

十一、其他

  1. 一些特殊的方法

名称 说明
__init__(self,...) 这个方法在新建对象恰好要被返回使用之前被调用。
__del__(self) 恰好在对象要被删除之前调用。
__str__(self) 在我们对对象使用print语句或是使用str()的时候调用。
__lt__(self,other) 当使用 小于 运算符(<)的时候调用。类似地,对于所有的运算符(+,>等等)都有特殊的方法。
__getitem__(self,key) 使用x[key]索引操作符的时候调用。
__len__(self) 对序列对象使用内建的len()函数的时候调用。

  下面的类中定义了上表中的方法:

class Array:
__list = [] def __init__(self):
print "constructor" def __del__(self):
print "destructor" def __str__(self):
return "this self-defined array class" def __getitem__(self, key):
return self.__list[key] def __len__(self):
return len(self.__list) def Add(self, value):
self.__list.append(value) def Remove(self, index):
del self.__list[index] def DisplayItems(self):
print "show all items----"
for item in self.__list:
print item arr = Array() #constructor
print arr #this self-defined array class
print len(arr) #0
arr.Add(1)
arr.Add(2)
arr.Add(3)
print len(arr) #3
print arr[0] #1
arr.DisplayItems()
#show all items----
#1
#2
#3
arr.Remove(1)
arr.DisplayItems()
#show all items----
#1
#3
#destructor

  2. 综合列表

    通过列表综合,可以从一个已有的列表导出一个新的列表。

list1 = [1, 2, 3, 4, 5]
list2 = [i*2 for i in list1 if i > 3] print list1 #[1, 2, 3, 4, 5]
print list2 #[8, 10]

  3. 函数接收元组/列表/字典

    当函数接收元组或字典形式的参数的时候,有一种特殊的方法,使用*和**前缀。该方法在函数需要获取可变数量的参数的时候特别有用。

    由于在args变量前有*前缀,所有多余的函数参数都会作为一个元组存储在args中。如果使用的是**前缀,多余的参数则会被认为是一个字典

  的键/值对。

def powersum(power, *args):
total = 0
for i in args:
total += pow(i, power)
return total print powersum(2, 1, 2, 3) #14
def displaydic(**args):
for key,value in args.items():
print "key:%s;value:%s" % (key, value) displaydic(a="one", b="two", c="three")
#key:a;value:one
#key:c;value:three
#key:b;value:two

  4. lambda

    lambda语句被用来创建新的函数对象,并在运行时返回它们。lambda需要一个参数,后面仅跟单个表达式作为函数体,而表达式的值被这个

  新建的函数返回。 注意,即便是print语句也不能用在lambda形式中,只能使用表达式。

func = lambda s: s * 3
print func("peter ") #peter peter peter func2 = lambda a, b: a * b
print func2(2, 3) #6

  5. exec/eval

    exec语句用来执行储存在字符串或文件中的Python语句;eval语句用来计算存储在字符串中的有效Python表达式。

cmd = "print 'hello world'"
exec cmd #hello world expression = "10 * 2 + 5"
print eval(expression) #25

  6. assert

    assert语句用来断言某个条件是真的,并且在它非真的时候引发一个错误--AssertionError

flag = True

assert flag == True

try:
assert flag == False
except AssertionError, err:
print "failed"
else:
print "pass"

  7. repr函数

    repr函数用来取得对象的规范字符串表示。反引号(也称转换符)可以完成相同的功能。

    注意,在大多数时候有eval(repr(object)) == object。

    可以通过定义类的__repr__方法来控制对象在被repr函数调用的时候返回的内容。

arr = [1, 2, 3]
print `arr` #[1, 2, 3]
print repr(arr) #[1, 2, 3]

十二、练习

    实现一个通讯录,主要功能:添加、删除、更新、查询、显示全部联系人。

 1 import cPickle
2 import os
3 import sys
4
5 class Contact:
6 def __init__(self, name, phone, mail):
7 self.name = name
8 self.phone = phone
9 self.mail = mail
10
11 def Update(self, name, phone, mail):
12 self.name = name
13 self.phone = phone
14 self.mail = mail
15
16 def display(self):
17 print "name:%s, phone:%s, mail:%s" % (self.name, self.phone, self.mail)
18
19
20 # begin
21
22 # file to store contact data
23 data = os.getcwd() + os.sep + "contacts.data"
24
25 while True:
26 print "-----------------------------------------------------------------------"
27 operation = raw_input("input your operation(add/delete/modify/search/all/exit):")
28
29 if operation == "exit":
30 sys.exit()
31
32 if os.path.exists(data):
33 if os.path.getsize(data) == 0:
34 contacts = {}
35 else:
36 f = file(data)
37 contacts = cPickle.load(f)
38 f.close()
39 else:
40 contacts = {}
41
42 if operation == "add":
43 flag = False
44 while True:
45 name = raw_input("input name(exit to back choose operation):")
46 if name == "exit":
47 flag = True
48 break
49 if name in contacts:
50 print "the name already exists, please input another or input 'exit' to back choose operation"
51 continue
52 else:
53 phone = raw_input("input phone:")
54 mail = raw_input("input mail:")
55 c = Contact(name, phone, mail)
56 contacts[name] = c
57 f = file(data, "w")
58 cPickle.dump(contacts, f)
59 f.close()
60 print "add successfully."
61 break
62 elif operation == "delete":
63 name = raw_input("input the name that you want to delete:")
64 if name in contacts:
65 del contacts[name]
66 f = file(data, "w")
67 cPickle.dump(contacts, f)
68 f.close()
69 print "delete successfully."
70 else:
71 print "there is no person named %s" % name
72 elif operation == "modify":
73 while True:
74 name = raw_input("input the name which to update or exit to back choose operation:")
75 if name == "exit":
76 break
77 if not name in contacts:
78 print "there is no person named %s" % name
79 continue
80 else:
81 phone = raw_input("input phone:")
82 mail = raw_input("input mail:")
83 contacts[name].Update(name, phone, mail)
84 f = file(data, "w")
85 cPickle.dump(contacts, f)
86 f.close()
87 print "modify successfully."
88 break
89 elif operation == "search":
90 name = raw_input("input the name which you want to search:")
91 if name in contacts:
92 contacts[name].display()
93 else:
94 print "there is no person named %s" % name
95 elif operation == "all":
96 for name, contact in contacts.items():
97 contact.display()
98 else:
99 print "unknown operation"

python基础语法(4)的更多相关文章

  1. python之最强王者(2)——python基础语法

    背景介绍:由于本人一直做java开发,也是从txt开始写hello,world,使用javac命令编译,一直到使用myeclipse,其中的道理和辛酸都懂(请容许我擦干眼角的泪水),所以对于pytho ...

  2. Python 基础语法(三)

    Python 基础语法(三) --------------------------------------------接 Python 基础语法(二)------------------------- ...

  3. Python 基础语法(四)

    Python 基础语法(四) --------------------------------------------接 Python 基础语法(三)------------------------- ...

  4. Python 基础语法(二)

    Python 基础语法(二) --------------------------------------------接 Python 基础语法(一) ------------------------ ...

  5. Python 基础语法

    Python 基础语法 Python语言与Perl,C和Java等语言有许多相似之处.但是,也存在一些差异. 第一个Python程序 E:\Python>python Python 3.3.5 ...

  6. 吾八哥学Python(四):了解Python基础语法(下)

    咱们接着上篇的语法学习,继续了解学习Python基础语法. 数据类型大体上把Python中的数据类型分为如下几类:Number(数字),String(字符串).List(列表).Dictionary( ...

  7. python学习第五讲,python基础语法之函数语法,与Import导入模块.

    目录 python学习第五讲,python基础语法之函数语法,与Import导入模块. 一丶函数简介 1.函数语法定义 2.函数的调用 3.函数的文档注释 4.函数的参数 5.函数的形参跟实参 6.函 ...

  8. python学习第四讲,python基础语法之判断语句,循环语句

    目录 python学习第四讲,python基础语法之判断语句,选择语句,循环语句 一丶判断语句 if 1.if 语法 2. if else 语法 3. if 进阶 if elif else 二丶运算符 ...

  9. Python基础语法(三)

    Python基础语法(三) 1. 数值型数据结构 1.1 要点 在之前的博客也有提到,数值型数据结构在这里就不过多介绍了.在这里提及一些需要知道的知识点. int.float.complex.bool ...

  10. python学习第三讲,python基础语法之注释,算数运算符,变量.

    目录 python学习第三讲,python基础语法之注释,算数运算符,变量. 一丶python中的基础语法,注释,算数运算符,变量 1.python中的注释 2.python中的运算符. 3.pyth ...

随机推荐

  1. android 图片进度条

    png图片 代码 ImageView loading=getActivity().findViewById(R.id.pro_loading); LinearInterpolator lin = ne ...

  2. 黑马程序员_ JAVA中的多线程

    ------- android培训.java培训.期待与您交流! ---------- 尽管线程对象的常用方法可以通过API文档来了解,但是有很多方法仅仅从API说明是无法详细了解的. 本来打算用一节 ...

  3. Remark

    // create by kim 20140805 public void Remark_insertChangeHeader(Editor e) { userinfo userInfo; ; e.u ...

  4. 系统中定义VOMapping的时候注意大小写

    VOMapping中的第一个参数一定要严格按照大小写(缩写的单词容易错): 例如:VO中的定义: private CntVOEnums.EnumIVRStage ivrStage; 实际反射找这个字段 ...

  5. Orcle常用语句

    在SQLPlus界面的操作语句: 查看\设置每行内显示的字符数:show\set linesize [linesize] 查看\设置一次显示的行数:show\set pagesize [pagesiz ...

  6. 【转】你真的理解Python中MRO算法吗?

    你真的理解Python中MRO算法吗? MRO(Method Resolution Order):方法解析顺序. Python语言包含了很多优秀的特性,其中多重继承就是其中之一,但是多重继承会引发很多 ...

  7. windows下gethostbyname 调用失败

    gethostbyname()函数属于WinSock API库,而在使用WinSock API之前,必须调用WSAStartup函数,只有该函数成功返回(表示应用程序与WinSock库成功地建立起连接 ...

  8. druid的安装

    最近想玩druid.druid的底层是fastbit索引的列式存储.采用分布式的zookeeper调度.实时大数据分析软件.主要针对OLAP操作. 搭环境搭环境.druid的核心成员成立了一个叫imp ...

  9. ZZ : Ubuntu:永久修改MAC地址

    方法一: 1)编辑“/etc/init.d/rc.local”文件(sudo gedit /etc/init.d/rc.local) 2)在此配置文件的最后面加上如(Ubuntu:修改网卡的MAC地址 ...

  10. docker--wekan安装

    最近因为搭建开源看板网站的需要,玩了下docker 一开始在redhat上安装docker wget http://mirrors.163.com/.help/CentOS7-Base-163.rep ...