http://developer.51cto.com/art/201207/347006.htm python十分钟入门
http://sebug.net/paper/python/ 简明python教程
Python(蟒蛇)是一种动态解释型的编程语言。Python可以在Windows、UNIX、MAC等多种操作系统上使用,也可以在Java、.NET开发平台上使用。
1 Python使用C语言开发,但是Python不再有C语言中的指针等复杂的数据类型。
2 Python具有很强的面向对象特性,而且简化了面向对象的实现。它消除了保护类型、抽象类、接口等面向对象的元素。
3 Python代码块使用空格或制表符缩进的方式分隔代码。
4 Python仅有31个保留字,而且没有分号、begin、end等标记。
5 Python是强类型语言,变量创建后会对应一种数据类型,出现在统一表达式中的不同类型的变量需要做类型转换。
python2与python3是目前主要的两个版本。
如下两种情况下,建议使用python2:
1 你无法完全控制你即将部署的环境时;
2 你需要使用一些特定的第三方包或扩展时;
python3是官方推荐的且是未来全力支持的版本,目前很多功能提升仅在python3版本上进行。
1 创建hello.py
2 编写程序:
#!/usr/bin/python # Filename : helloworld.py if __name__ == '__main__': print 'Hello World'3 运行程序:
python ./helloworld.py
# -* - coding: UTF-8 -* -
3 如下注释用于指定解释器(它被称作 组织行 ——源文件的头两个字符是#!,后面跟着一个程序。这行告诉你的Linux/Unix系统当你 执行 你的程序的时候,它应该运行哪个解释器)。
#! /usr/bin/python
4 注意python中也有main函数:
#hello.py def foo(): str="function" print(str); if __name__=="__main__": print("main") foo()其中if __name__=="__main__":这个程序块类似与Java和C语言的中main(主)函数
C:\work\python\divepy>python hello.py main function在Python Shell中运行结果
>>> import hello >>> hello.foo() function >>> hello.__name__ 'hello' >>>可以发现这个内置属性__name__自动的发生了变化。
import py_compile py_compile.compile(‘hello.py’)4 经过优化的源文件会以.pyo为后缀,即优化代码。它也不能直接用文本编辑器修改,如下命令可用来生成pyo文件:
python -O -m py_complie hello.py
需要模块:import sys
参数个数:len(sys.argv)
脚本名: sys.argv[0]
参数1: sys.argv[1]
参数2: sys.argv[2]
x = 1 print id(x) x = 2 print id(x)3 如果变量没有赋值,则python认为该变量不存在
_a = 1 _b = 2use_global.py中引用全局变量:
import gl def fun(): print gl._a print gl._b fun()
class _const: class ConstError(TypeError): pass def __setattr__(self,name,vlaue): if self.__dict__.has_key(name): raise self.ConstError, “Can’t rebind const(%s)”%name self.__dict__[name]=value import sys sys.modules[__name__]=_const()
注意浮点数:
3.23和52.3E-4是浮点数的例子。E标记表示10的幂。在这里,52.3E-4表示52.3 * 10-4。
(-5+4j)和(2.3-4.6j)是复数的例子。
注意字符串:
使用单引号(')你可以用单引号指示字符串,就如同'Quote me on this'这样。所有的空白,即空格和制表符都照原样保留。
使用双引号(")在双引号中的字符串与单引号中的字符串的使用完全相同,例如"What's your name?"。
使用三引号('''或""")利用三引号,你可以指示一个多行的字符串。你可以在三引号中自由的使用单引号和双引号。
注意字符串中的转义字符:
用\'来指示单引号——注意这个反斜杠。现在你可以把字符串表示为'What\'s your name?'。另一个表示这个特别的字符串的方法是"What's your name?",即用双引号。另外,你可以用转义符\\来指示反斜杠本身。
自然字符串:
如果你想要指示某些不需要如转义符那样的特别处理的字符串,那么你需要指定一个自然字符串。自然字符串通过给字符串加上前缀r或R来指定。例如r"Newlines are indicated by \n"。
Unicode字符串:
Python允许你处理Unicode文本——你只需要在字符串前加上前缀u或U。例如,u"This is a Unicode string."。
int(x [,base ]) 将x转换为一个整数
long(x [,base ]) 将x转换为一个长整数
float(x ) 将x转换到一个浮点数
complex(real [,imag ]) 创建一个复数
str(x ) 将对象 x 转换为字符串
repr(x ) 将对象 x 转换为表达式字符串
eval(str ) 用来计算在字符串中的有效Python表达式,并返回一个对象
tuple(s ) 将序列 s 转换为一个元组
list(s ) 将序列 s 转换为一个列表
chr(x ) 将一个整数转换为一个字符
unichr(x ) 将一个整数转换为Unicode字符
ord(x ) 将一个字符转换为它的整数值
hex(x ) 将一个整数转换为一个十六进制字符串
oct(x ) 将一个整数转换为一个八进制字符串
5 逻辑表达式中and表示逻辑与,or表示逻辑或,not表示逻辑非
6 exec和eval语句
exec语句用来执行储存在字符串或文件中的Python语句。例如,我们可以在运行时生成一个包含Python代码的字符串,然后使用exec语句执行这些语句。下面是一个简单的例子。
>>> exec 'print "Hello World"' Hello Worldeval语句用来计算存储在字符串中的有效Python表达式。下面是一个简单的例子。
>>> eval('2*3') 6
1. 用os.system(cmd) 不过取不了返回值
2.用os.popen(cmd) 要得到命令的输出内容,只需再调用下read()或readlines()等 如a=os.popen(cmd).read()
if (表达式) :#其实表达式可以没有括号 语句1 else : 语句2
if (表达式) : 语句1 elif (表达式) : 语句2 … elif (表达式) : 语句n else : 语句m
if (表达式1) : if (表达式2) : 语句1 elif (表达式3) : 语句2 … else: 语句3 elif (表达式n) : … else : …
while(表达式) : … else : …
for 变量 in 集合 : … else : …
python不支持类似c的for(i=0;i<5;i++)这样的循环语句,但可以借助range模拟:
for x in range(0,5,2): print x
range(1,5)给出序列[1, 2, 3, 4]
range(1,5,2)给出[1,3]
举例:
#!/usr/bin/python # Filename: while.py number = 23 running = True while running: guess = int(raw_input('Enter an integer : ')) if guess == number: print 'Congratulations, you guessed it.' running = False # this causes the while loop to stop elif guess < number: print 'No, it is a little higher than that' else: print 'No, it is a little lower than that' else: print 'The while loop is over.' # Do anything else you want to do here print 'Done'
#!/usr/bin/python # Filename: continue.py while True: s = raw_input('Enter something : ') if s == 'quit': break if len(s) < 3: continue print 'Input is of sufficient length' # Do other kinds of processing here...
V1 if X else V2完美的解决方案是在《python核心编程中提到的》:
如果你来自 C/C++ 或者是 Java 世界, 那么你很难忽略的一个事实就是 Python 在很长的一段时间里没有条件表达式(C ? X : Y), 或称三元运算符. ( C 是条件表达式; X 是 C 为 True 时的结果, Y 是 C 为 False 时的结果)
贵铎·范·罗萨姆一直拒绝加入这样的功能, 因为他认为应该保持代码简单, 让程序员不轻易出错. 不过在十年多后, 他放弃了, 主要是因为人们试着用and 和 or 来模拟它, 但大多都是错误的. 根据 FAQ , 正确的方法(并不唯一)是(C and [X] or [Y])[0] .
唯一的问题是社区不同意这样的语法. (你可以看一看 PEP 308, 其中有不同的方案.) 对于Python 的这一问题,人们表达了极大的诉求.贵铎·范·罗萨姆最终选择了一个最被看好(也是他最喜欢)的方案, 然后把它运用于标准库中的一些模块. 根据 PEP , "这个评审通过考察大量现实世界的案例, 包含不同的应用, 以及由不同程序员完成的代码." 最后 Python 2.5 集成的语法确定为: X if C else Y .
tuple_name=("apple",5,tuple,"orange")解释:tuple[2]
python中一种内置的数据结构。元组由不同的元素组成,每个元素可以存储不同类型的数据,如字符串、数字甚至元素。元组是写保护的,即元组创建之后不能再修改。元组往往代表一行数据,而元组中的元素代表不同的数据项。可以把元组看做不可修改的数组。创建元组示例如下:
tuple_name=("apple",5,tuple,"orange")
我们可以通过一对方括号来指明某个项目的位置从而来访问元组中的项目,就像我们对列表的用法一样。这被称作 索引 运算符。我们使用new_zoo[2]来访问new_zoo中的第三个项目。我们使用new_zoo[2][2]来访问new_zoo元组的第三个项目的第三个项目。
含有0个或1个项目的元组:
一个空的元组由一对空的圆括号组成,如myempty = ()。然而,含有单个元素的元组就不那么简单了。你必须在第一个(唯一一个)项目后跟一个逗号,这样Python才能区分元组和表达式中一个带圆括号的对象。即如果你想要的是一个包含项目2的元组的时候,你应该指明singleton = (2 , )。
元组基本上同列表,但不同的是元组用圆括号表示,元组中的值不可以改变,相当于一个常量。
list=["apple","banana","grage","orange"]解释:list[2]
列表和元组相似,也由一组元素组成,列表可以实现添加、删除和查找操作,元素的值可以被修改。列表是传统意义上的数组。列表创建示例如下:
list=["apple","banana","grage","orange"]
使用:
可以使用append方法来在尾部追加元素,使用remove来删除元素。
# -* - coding: UTF-8 -* - #!/usr/bin/python # Filename: using_list.py list = ['apple', 'mango', 'carrot', 'banana'] #列表长度 len(list) #遍历列表 # 注意末尾的逗号,我们在print语句的结尾使用了一个 逗号 来消除每个print语句自动打印的换行符。这样做有点难看,不过确实简单有效。 print 'These items are:', for item in list: print item, #增加列表项 list.append('rice') #列表排序 #注意sort()函数改变原来的列表,函数返回值是空值即None list.sort() #获得排序列表副本1 list2 = list[:] list2.sort() #获得排序列表副本2 list3 = sorted(list) #删除列表项 del list[0]
帮助:
dict={"a":"apple", "b":"banana", "g":"grage", "o":"orange"}解释:
由键-值对组成的集合,字典中的值通过键来引用。键和值之间用冒号隔开,键-值对之间用逗号隔开,并且被包含在一对花括号中。注意,键必须是唯一的。记住字典中的键/值对是没有顺序的。字典是dict类的实例/对象。创建示例如下:
dict={"a":"apple", "b":"banana", "g":"grage", "o":"orange"}
使用:dict[key]
# -* - coding: UTF-8 -* - #!/usr/bin/python # Filename: using_dict.py addressBook = { 'Swaroop' : '[email protected]', 'Larry' : '[email protected]', 'Matsumoto' : '[email protected]', 'Spammer' : '[email protected]' } # 使用字典:dict[key] print "Swaroop's address is %s" % addressBook['Swaroop'] # 增加字典项:dict[newKey]=newValue addressBook['Guido'] = '[email protected]' # 删除字典项:del dict[key] del addressBook['Spammer'] # 字典长度:len(dict) print '\nThere are %d contacts in the address-book\n' % len(addressBook) # 遍历字典: for name, address in addressBook.items(): print 'Contact %s at %s' % (name, address) # 查找字典值: if 'Guido' in addressBook: # 或 addressBook.has_key('Guido') print "\nGuido's address is %s" % addressBook['Guido'] #对字典按键排序,元组列表的形式返回 d={"ok":1,"no":2} sorted(d.items, key=lambda d:d[0]) #[('no', 2), ('ok', 1)] 对字典按值排序,元组列表的形式返回 d={"ok":1,"no":2} sorted(d.items, key=lambda d:d[1]) #[('ok', 1), ('no', 2)]
帮助:
可以通过help(dict)获得完整的知识。
解释:
1,列表、元组和字符串都是序列。
2,序列的两个主要特点是索引操作符和切片操作符。
索引操作符让我们可以从序列中抓取一个特定项目。
切片操作符让我们能够获取序列的一个切片,即一部分序列。
使用:
#!/usr/bin/python # Filename: seq.py shoplist = ['apple', 'mango', 'carrot', 'banana'] # Indexing or 'Subscription' operation print 'Item 0 is', shoplist[0] print 'Item 1 is', shoplist[1] print 'Item 2 is', shoplist[2] print 'Item 3 is', shoplist[3] print 'Item -1 is', shoplist[-1] print 'Item -2 is', shoplist[-2] # Slicing on a list print 'Item 1 to 3 is', shoplist[1:3] print 'Item 2 to end is', shoplist[2:] print 'Item 1 to -1 is', shoplist[1:-1] print 'Item start to end is', shoplist[:] # Slicing on a string name = 'swaroop' print 'characters 1 to 3 is', name[1:3] print 'characters 2 to end is', name[2:] print 'characters 1 to -1 is', name[1:-1] print 'characters start to end is', name[:]
解释:
通过列表综合,可以从一个已有的列表导出一个新的列表。例如,你有一个数的列表,而你想要得到一个对应的列表,使其中所有大于2的数都是原来的2倍。对于这种应用,列表综合是最理想的方法。
# -* - coding: UTF-8 -* - #!/usr/bin/python # Filename: list_comprehension.py listone = [2, 3, 4] listtwo = [2*i for i in listone if i > 2] print listtwo # 结果是[6,8]
python程序由包(package)、模块(module)和函数组成。包是由一系列模块组成的集合。模块是处理某一类问题的函数和类的集合。包就是一个完成特定任务的工具箱。包必须含有一个__init__.py文件,它用于标识当前文件夹是一个包。python的程序是由一个个模块组成的。模块把一组相关的函数或代码组织到一个文件中,一个文件即是一个模块。模块由代码、函数和类组成。导入模块使用import语句。包的作用是实现程序的重用。函数是一段可以重复多次调用的代码。
通常把内建函数成为BIF(built-in functions)
函数定义示例如下:
#!/usr/bin/python # Filename: seq.py def arithmetic(x,y,operator): result={ "+":x+y, "-":x-y, "*":x*y, "/":x/y } return result[operator] print arithmetic(1,2,"+")函数返回值可以用return来控制, 除非你提供你自己的return语句,每个函数都在结尾暗含有return None语句。
函数内部的全局变量
#!/usr/bin/python # Filename: func_global.py def func(): global x #这里声明使用外部定义的全局的x。 print 'x is', x #将输出外部值50 x = 2 print 'Changed local x to', x #这里外部值x真正的被改变了 x = 50 func() print 'Value of x is', x
文档字符串的惯例是一个多行字符串,它的首行以大写字母开始,句号结尾。第二行是空行,从第三行开始是详细的描述。 强烈建议 你在你的函数中使用文档字符串时遵循这个惯例。
pass语句在Python中表示一个空的语句块。
# -* - coding: UTF-8 -* - #!/usr/bin/python # Filename: func_doc.py #这里的y=1是默认参数 def func(x, y=1): '''This is the DocStrings func(x,y=1) ''' pass #这句表示空语句 print func(3) #由于函数没有return的话默认有一句 return None,所以这里输出None print func.__doc__ #这里调用直接输出DocStrings
如果要打印本文件而不是其他模块的docString,我想出来了这么一个办法:
A.py
''' Created on 2012-10-10 @author: xing.gexing ''' import A if __name__=="__main__": print A.__doc__
如果你想要直接输入argv变量到你的程序中(避免在每次使用它时打sys.),那么你可以使用from sys import argv语句。如果你想要输入所有sys模块使用的名字,那么你可以使用from sys import *语句。这对于所有模块都适用。一般说来,应该避免使用from..import而使用import语句,因为这样可以使你的程序更加易读,也可以避免名称的冲突。也可以直接import sys
创建如下模块:mymodule.py
#!/usr/bin/python # Filename: mymodule.py def sayhi(): print 'Hi, this is mymodule speaking.' version = '0.1' # End of mymodule.py测试用例1:mymodule_demo.py
#!/usr/bin/python # Filename: mymodule_demo.py import mymodule mymodule.sayhi() print 'Version', mymodule.version测试用例2:mymodule_demo.py
#!/usr/bin/python # Filename: mymodule_demo2.py from mymodule import sayhi, version # Alternative: # from mymodule import * sayhi() print 'Version', version
元组、列表: 当要使函数接收元组或字典形式的参数的时候,有一种特殊的方法,它分别使用*和**前缀。这种方法在函数需要获取可变数量的参数的时候特别有用。
字典: 由于在args变量前有*前缀,所有多余的函数参数都会作为一个元组存储在args中。如果使用的是**前缀,多余的参数则会被认为是一个字典的键/值对。
# -* - coding: UTF-8 -* - #!/usr/bin/python # 1,函数的参数是元组/列表 # 后续参数1,2作为元组(1,2)传入 def a1(*args): if len(args)==0: print 'None' else: print args a1() # 输出None a1(1,2) # 输出(1, 2) # 2,函数的参数是字典 # 后续参数作为字典{x:1,y:2}传入 def a2(**args): if len(args)==0: print 'None' else: print args a2() # 输出None a2(x=1,y=2) # 输出{'y': 2, 'x': 1}注意遍历返回的顺序与形参位置顺序相反<span style="color: rgb(51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px; text-align: left; "></span>
另外特别地,对于传递字典,有这样一些结论:
#dict1={x:1,y:2} # NameError: name 'x' is not defined,除非这个x变量事先已经被定义了。 dict2={'x':1,'y':2} #dict3={1:x,2:y} # NameError: name 'x' is not defined,同理。 dict4={1:'x',2:'y'} # 定义函数参数为字典 def a(**args): print args a(x=1,y=2) # 我的理解是,这里估计先要通过函数的语法检查,所以=左边必须是变量,然后才被识别为字符串'x',所以这种传递字典很局限,只能传递key为字符串的字典。 #a('x'=1,'y'=2) #a(1=x,2=y) #a(1='x',2='y')
如果要传递任意的字典,不如这样:
def a(dict) dict={1:'x',2='y'} a(dict)
format="%s%d" % (str1,num) print format2 用+进行字符串的合并:
str1="hello" str2="world" result=str1+str2
3 字符串截取可以通过索引/切片,也可以通过split函数。
words = line.split("\t")返回给words的是一个列表。
word="world" print word[0:3]5 python使用==和!=来进行字符串比较。如果比较的两个变量的类型不相同,那么结果必然为不同。
# -* - coding: UTF-8 -* - #!/usr/bin/python # Filename: str_methods.py # 字符串name name = 'Swaroop' # name.startswith("") startwith方法是用来测试字符串是否以给定字符串开始 if name.startswith('Swa'): print 'Yes, the string starts with "Swa"' # in in操作符用来检验一个给定字符串是否为另一个字符串的一部分 if 'a' in name: print 'Yes, it contains the string "a"' # name.find("") find方法用来找出给定字符串在另一个字符串中的位置,或者返回-1以表示找不到子字符串 if name.find('war') != -1: print 'Yes, it contains the string "war"' # str类也有以一个作为分隔符的字符串join序列的项目的整洁的方法,它返回一个生成的大字符串 delimiter = '_*_' mylist = ['Brazil', 'Russia', 'India', 'China'] print delimiter.join(mylist)
读取文件可以使用readline()函数、readlines()函数和read函数。
写入文件可以使用write()、writelines()函数
# -* - coding: UTF-8 -* - #!/usr/bin/python # Filename: using_file.py poem = '''\ Programming is fun When the work is done if you wanna make your work also fun: use Python! ''' # 以写模式打开文件,模式可以为读模式('r')、写模式('w')或追加模式('a') f = file('poem.txt', 'w') # 写入内容 f.write(poem) # 关闭文件 f.close() # 以读模式打开文件,不指定mode默认为读 f = file('poem.txt') # 逐行读取内容 while True: line = f.readline() if len(line) == 0: # 长度为0表示读到EOF break print line, # 注意逗号表示避免换行 # 关闭文件 f.close()
read_file = open("new_tablelist.txt").read() write_file = open("a.txt","w") for words in read_file.split("\n"): if words != "": write_file.write(words.split(":")[1]+"\n") write_file.close()
read_file = open(sys.argv[1]).read() write_file = open(sys.argv[2],"w") for line in read_file.split("\r\n"): if line != "": words = line.split("\t") if words[0] == "": continue rank = words[0] write_file.write(rank+"\t") cmd = "./hex2bin "+words[1][2:] name = os.popen(cmd).read() write_file.write(name+"\t") server = dict_server[words[2]] write_file.write(server+"\t") score = words[3] write_file.write(score+"\t") write_file.write("\n") write_file.close()
Python提供一个标准的模块,称为pickle。使用它你可以在一个文件中储存任何Python对象,之后你又可以把它完整无缺地取出来。这被称为 持久地 储存对象。
还有另一个模块称为cPickle,它的功能和pickle模块完全相同,只不过它是用C语言编写的,因此要快得多(比pickle快1000倍)。你可以使用它们中的任一个,而我们在这里将使用cPickle模块。记住,我们把这两个模块都简称为pickle模块。
# -* - coding: UTF-8 -* - #!/usr/bin/python # Filename: pickling.py import cPickle as p #import pickle as p # 建立两个对象 shoplistfile = 'shoplist.data' shoplist = ['apple', 'mango', 'carrot'] # 将对象写入文件 f = file(shoplistfile, 'w') p.dump(shoplist, f) f.close() # 删除对象 del shoplist # 从文件中读取对象 f = file(shoplistfile) storedlist = p.load(f) print storedlist
class Fruit: def grow(self): print "Fruit grow"
类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称,但是在调用这个方法的时候你不为这个参数赋值,Python会提供这个值。这个特别的变量指对象本身,按照惯例它的名称是self。
Python中的self等价于C++中的self指针和Java、C#中的this参考。
假如你有一个类称为MyClass和这个类的一个实例MyObject。当你调用这个对象的方法MyObject.method(arg1, arg2)的时候,这会由Python自动转为MyClass.method(MyObject, arg1, arg2)——这就是self的原理了。
2 当一个对象被创建后,包含了三方面的特性,即对象的句柄、属性和方法。创建对象的方法:
fruit = Fruit() fruit.grow()
3 python没有保护类型的修饰符
4 类的方法也分为公有方法和私有方法。私有函数不能被该类之外的函数调用,私有的方法也不能被外部的类或函数调用。6 python的构造函数名为__init__,析构函数名为__del__
# -* - coding: UTF-8 -* - #!/usr/bin/python # Filename: objvar.py class Person: '''Represents a person.''' # 这是类的变量 population = 0 # 构造函数 def __init__(self, name): '''Initializes the person's data.''' #类的文档字符串 # 这里是self.name,所以这个name是对象的变量 self.name = name print '(Initializing %s)' % self.name # 构造函数使得类的变量population+1 Person.population += 1 # 析构函数 def __del__(self): '''I am dying.''' #方法的文档字符串 print '%s says bye.' % self.name Person.population -= 1 if Person.population == 0: print 'I am the last one.' else: print 'There are still %d people left.' % Person.population def sayHi(self): '''Greeting by the person. Really, that's all it does.''' print 'Hi, my name is %s.' % self.name def howMany(self):#如果这个函数要调用本类的sayHi(self),需要操作self.sayHi() '''Prints the current population.''' if Person.population == 1: print 'I am the only person here.' else: print 'We have %d persons here.' % Person.population # 我们可以在运行时使用Person.__doc__和Person.sayHi.__doc__来分别访问类与方法的文档字符串。 swaroop = Person('Swaroop') swaroop.sayHi() swaroop.howMany() kalam = Person('Abdul Kalam') kalam.sayHi() kalam.howMany() swaroop.sayHi() swaroop.howMany()
class Apple(Fruit): def …
# -* - coding: UTF-8 -* - #!/usr/bin/python # Filename: inherit.py class SchoolMember: '''Represents any school member.''' def __init__(self, name, age): self.name = name self.age = age print '(Initialized SchoolMember: %s)' % self.name def tell(self): '''Tell my details.''' print 'Name:"%s" Age:"%s"' % (self.name, self.age), class Teacher(SchoolMember): '''Represents a teacher.''' def __init__(self, name, age, salary): SchoolMember.__init__(self, name, age) self.salary = salary print '(Initialized Teacher: %s)' % self.name def tell(self): SchoolMember.tell(self) print 'Salary: "%d"' % self.salary class Student(SchoolMember): '''Represents a student.''' def __init__(self, name, age, marks): SchoolMember.__init__(self, name, age) self.marks = marks print '(Initialized Student: %s)' % self.name def tell(self): SchoolMember.tell(self) print 'Marks: "%d"' % self.marks t = Teacher('Mrs. Shrividya', 40, 30000) s = Student('Swaroop', 22, 75) print # prints a blank line members = [t, s] for member in members: member.tell() # works for both Teachers and Students
8 对象的深度拷贝
要想取得深层拷贝,必须使用切片操作符来获取整个拷贝。
# -* - coding: UTF-8 -* - #!/usr/bin/python # Filename: reference.py # mylist和shoplist都只想同一个内存对象。 shoplist = ['apple', 'mango', 'carrot', 'banana'] mylist = shoplist # mylist和shoplist都少了apple del shoplist[0] # 这才是深层复制,mylist和shoplist对应两个不同的对象了。 mylist = shoplist[:] # 这里只删除了mylist的第一个单词 del mylist[0]
直接在python cmd里这样测试,尝试读取用户的一段输入。按Ctrl-d,看一下会发生什么:
>>> s = raw_input('Enter something --> ') Enter something --> Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> s = raw_input('Enter something --> ') EOFError: EOF when reading a line
# -* - coding: UTF-8 -* - #!/usr/bin/python # Filename: try_except.py import sys try: s = raw_input('Enter something --> ') except EOFError as err: print '\nWhy did you do an EOF on me?'+str(err) sys.exit # 直接退出 except: print '\nSome error/exception occurred.' print 'Done'
# -* - coding: UTF-8 -* - #!/usr/bin/python # Filename: raising.py # 定义一个异常类ShortInputException,该类继承自Exception class ShortInputException(Exception): '''A user-defined exception class.''' def __init__(self, length, atleast):#self是必须的,length表示当前输入长度,atleast表示应输入长度 Exception.__init__(self) self.length = length # 对象的私有变量 self.atleast = atleast # 对象的私有变量 try: s = raw_input('Enter something --> ') if len(s) < 3: raise ShortInputException(len(s), 3) # 主动抛出异常 except EOFError: print '\nWhy did you do an EOF on me?' except ShortInputException, x: print 'ShortInputException: The input was of length %d, was expecting at least %d' % (x.length, x.atleast) else: print 'No exception was raised.'测试结果:
>>> ================================ RESTART ================================ >>> Enter something --> Why did you do an EOF on me? >>> ================================ RESTART ================================ >>> Enter something --> ab ShortInputException: The input was of length 2, was expecting at least 3 >>> ================================ RESTART ================================ >>> Enter something --> abc No exception was raised. >>>
# -* - coding: UTF-8 -* - #!/usr/bin/python # Filename: finally.py import time try: f = file('poem.txt') while True: line = f.readline() if len(line) == 0:# len(line)==0表示读到文件EOF break time.sleep(2) print line, finally: f.close() print 'Cleaning up...closed the file'我们进行通常的读文件工作,但是我有意在每打印一行之前用time.sleep方法暂停2秒钟。这样做的原因是让程序运行得慢一些(Python由于其本质通常运行得很快)。在程序运行的时候,按Ctrl-c中断/取消程序。
例如打开文件操作:
try: f = open('a.txt') print f.readlines() finally: f.close()
如果使用with,则明显提高友好度:
with open('a.txt') as f: print f.readlines()为了我们自己的类也可以使用with, 只要给这个类增加两个函数__enter__, __exit__即可:
>>> class A: def __enter__(self): print 'in enter' def __exit__(self, e_t, e_v, t_b): print 'in exit' >>> with A() as a: print 'in with' in enter in with in exit
import os, sys import MySQLdb try: conn MySQLdb.connect(host=’localhost’,user=’root’,passwd=’’,db=’address’ except Exception,e: print e sys.exit() cursor=conn.cursor() sql=’insert into address(name, address) values(%s, %s)’ value=((“zhangsan”,”haidian”),(“lisi”,”haidian”)) try cursor.executemany(sql,values) except Exception, e: print e sql=”select * from address” cursor.execute(sql) data=cursor.fetchall() if data for x in data: print x[0],x[1] cursor.close() conn.close()
python[cpython] 的GIL规定每个时刻只能有一个线程访问python虚拟机,所以你要用python的多线程来做计算是很不合算的,但是对于IO密集型的应用,例如网络交互来说,python的多线程还是非常给力的。如果你是一个计算密集型的任务,非要用python来并行执行的话,有以下几个方法:
1 使用python的multiprocessing 模块,能够发挥多核的优势。
2 使用ironPython,但是这个只能在windows下用
3 使用pypy,这个可以实现真正的多线程。
Python中的easy_install工具很爽,它的作用类似于Php中的pear,或者Ruby中的gem,或者Perl中的cpan。
wget -q http://peak.telecommunity.com/dist/ez_setup.py python ez_setup.py
有时候可能需要再安装python-dev
sudo yum install python-devel
例如安装python的代码覆盖率工具:
sudo easy_install coverage