1、Python Intro把有空格trn的字符串标准化成words之间统一用1个空格分割的字符串str=“”First line Second line“”=“First line Second line”“”.join(str.split()求两个数的最大公约数:def gcd(a,b):while b!=0:a,b=b,a%breturn aPython是什么解释语言,不需要编译面向对象,所有的东西都是对象代码可读性好,易于维护语法简单,容易学习和理解,比c+/Java更适合初学者易于扩展胶水特性,可以和C/C+/Java/C#等混合编程非常成熟(20岁了!),内置200+模块,PYPI上有
2、1w+有非常活跃的社区快速开发(Java的3-5倍,C+的5-10倍)没有内存泄露,没有core dump跨平台(Linux/Unix/Windows/Mac)被广泛使用被评为2007年年度语言C+/PHP/Java/Ruby/Python/C/Go性能还行 Ruby/PHP Python Java/C#Erlang/Go import this dir(object)help(func)Python实践DBScanner监控统计类WEBPCL访问延时TDB错误日志乐斗活动统计企鹅抛弃和领养同步Python通过C+访问TDBSmartDirFlash Policysvr测试工具类SmartDi
3、r测试工具乐斗II测试工具C+-Python注意关键字,关键字不能做变量名没有采用缩进来组织代码块缩进要统一(不然不让你过),一般用2-4个空格,别用tab没有switch用if/elif/else吧可以的话,用dict没有?操作符,x?y:zPython2.5加了这种支持y if x else zC+-Python(2)创建对象不用newclass A(object):a=A()没有delete操作符,一般交给GC来管,要显式delete对象a=None对map来说,del dictkey 没有拷贝构造a=A()b=aa 和 b指向同一个对象int/string/tuple除外,创建后不能修
4、改C+-Python(3)可以多变量赋值(也叫bind)a,b,c=1,2,3list1=4,5,6/tuple1=(1,2,3)a,b,c=list1/tuple1没有make_pair,函数也能返回多个值def func():return 4,5,6a,b,c=func()对象/函数注释写哪里呢def func():A function that returns 3 consecutive ints,starting with 4 return 4,5,6help(func)可以直接查到注释里边可以有示例式的uint tests,python自动帮你测试!C+-Python(4)要遍历一个
5、list for(x=0;x Python(5)都有lambdag=lambdalambda x:x*2g(3)/(lambda(lambda x:x*2)(3)非常方便都有算法mapmap(lambda x:x*x*x,range(1,11)x*x*x for x in range(1,11)/叫做list再构造,性能优于map/fliter,当然更优于forfilterx for x in list1 if x%2!=0 and x%3!=0filter(lambda x:x%2!=0 and x%3!=0,range(2,25)applyapply(lambda*x:x*x,range(
6、2,10)reducereduce(lambda x,y:x+y,a)Sumsum(list1)/sum(x*x for x in list1)minMaxC+-Python(6)函数也是对象li=Larry,Curlyli.popgetattr(li,pop)getattr(li,append)(Moe)获取所有的函数列表methodList=method forfor method inin dir(object)ifif callable(getattr(object,method)想要初始化成员变量么class A(object):var1=/类变量 def _init_(self):
7、self.var2=/实例成员C+-Python(7)都有默认参数def func(object,spacing=10,collapse=1):func(5)func(5,12)func(5,collapse=1)func(spacing=1,object=5)都有可变参数*args(tuple)*kwargs(dict)def func(*args,*kwargs):print args,kwargsfoo(1,2,3,4)foo(a=1,b=2,c=3)foo(1,2,3,4,a=1,b=2,c=3)foo(a,1,None,a=1,b=2,c=3)BasicBasic types:num
8、bers,stringsContainer types:list,dictionaries,tuplesVariablesControl structuresFunctions&proceduresClasses&instancesModules&packagesExceptionsFiles&socketsStandard librariesNumbers和C+差不多12,3.14,0 xFF,0377,(-1+2)*3/4*5,abs(x),0 x=5移位/位操作1 0#1./2.-0.5,float(1)/2-0.5Python3.0以后改掉了不会溢出2*100-126765376L复数
9、直接能表达1j*2-(-1+0j)1+0.5j 这是个复数,j表示虚数部分整数也是对象(5)._str_()相当于str(5)Strings“hello”+“world”“helloworld”#字符串拼接“hello”*3“hellohellohello”#重复“hello”0“h”#索引“hello”-1“o”#最后1个“hello”1:4“ell”#截取/切片len(“hello”)5#长度“hello”98,bottles,of,beer,on,the,walldel a-1#-98,bottles,of,beerMore List Operations a=range(5)#0,1,
10、2,3,4 a.append(5)#0,1,2,3,4,5 a.pop()#0,1,2,3,45 a.insert(0,42)#42,0,1,2,3,4 a.pop(0)#0,1,2,3,45.5 a.reverse()#4,3,2,1,0 a.sort()#0,1,2,3,4Dictionaries就是map,关联容器d=duck:eend,water:water查找:dduck-eenddback#raises KeyError exceptionDelete,insert,overwrite:del dwater#duck:eenddback=rug#duck:eend,back:rug
11、dduck=duik#duck:duik,back:rugMore Dictionary OpsKeys,values,items:d.keys()-duck,backd.values()-duik,rugd.items()-(duck,duik),(back,rug)检查key是否存在:d.has_key(duck)-1;d.has_key(spam)-0Value可以是任何类型,Key嘛name:Guido,age:43,(hello,world):1,42:yes,flag:red,white,blueDictionary DetailsKey必须是hashable的类型:不能是不能是l
12、ists 或其他dictionariesDict不保持元素的顺序Tuplesmake_pair boost:tuple?key=(lastname,firstname)point=x,y,z#括号可以忽略x,y,z=point#取值lastname=key0singleton=(1,)#单个元素的元组要跟个,empty=()#空元组必须要有括号元组是immutable的,初始化后不能改变Variables不需要声明需要初始化使用未初始化的变量会抛异常不绑定类型if friendly:greeting=hello worldelse:greeting=12*2print greeting所有东西
13、都是”变量”functions,classes,modules都是Control Structuresif condition:statementselif condition:statements.else:statementswhile condition:statementsfor var in sequence:statementsbreakcontinueGrouping IndentationIn Python:for i in range(20):if i%3=0:print i if i%5=0:print Bingo!print-In C:for(i=0;i gcd._doc
14、_greatest common divisor gcd(12,20)4Classesclass name:documentation statements-or-class name(base1,base2,.):.statements 一般都是函数定义:def name(self,arg1,arg2,.):.以及类变量初始化Built-in methods_str_ 可以通过str(object)转成string_len_ 可以通过len(object)获得对象长度_nonzero_(_bool_ in 3.0)条件表达式判断,or/and运算_init_ 初始化_new_ 创建对象,_n
15、ew_是类成员函数现有_new_再有_init_int_ 可以通过int(object)转成int_add_ a+b会调a的_add_全部可以重载type()获取对象类型getattr()获取某个对象的某个属性值setattr()设置某个对象的某个属性值Example Classclass Stack:A well-known data structure def _init_(self):#初始化,一般叫构造函数 self.items=def push(self,x):self.items.append(x)def pop(self):x=self.items-1 del self.item
16、s-1 return x def empty(self):return len(self.items)=0 Using Classes创建对象x=Stack()调用成员函数x.empty()#-1x.push(1)#1x.empty()#-0 x.push(hello)#1,hellox.pop()#-hello#1获取实例成员变量:x.items#-1Subclassingclass FancyStack(Stack):stack with added ability to inspect inferior stack items def peek(self,n):peek(0)return
17、s top;peek(-1)returns item below that;etc.size=len(self.items)assert 0=n size return self.itemssize-1-nSubclassing(2)class LimitedStack(FancyStack):fancy stack with limit on stack size def _init_(self,limit):self.limit=limit FancyStack._init_(self)#base class constructor def push(self,x):assert len(
18、self.items)self.limit FancyStack.push(self,x)#super method callClass/Instance Variablesclass Connection:verbose=0#class variable def _init_(self,host):self.host=host#instance variable def debug(self,v):self.verbose=v#make instance variable!def connect(self):if self.verbose:#class or instance variabl
19、e?print connecting to,self.hostInstance Variable Rules调用成员变量和函数的查找顺序self.x:(1)实例成员,(2)类成员,(3)基类第一次给实例成员变量赋值会创建这个变量self.xModules每个py文件都是module(foo.py)functions,classes,variables使用之前先要import:import re;print re.match(a-z+,s)from re import match;print match(a-z+,s)别名:import re as regexfrom re import mat
20、ch as mPackagesModule的集合必须有 _init_.py fileImport:from P.Q.M import foo;print foo()from P.Q import M;print M.foo()import P.Q.M;print P.Q.M.foo()import P.Q.M as M;print M.foo()Catching Exceptionsdef foo(x):return 1/xdef bar(x):try:print foo(x)except ZeroDivisionError,message:print Cant divide by zero:
21、,messagebar(0)Try-finally:Cleanupf=open(file)try:process_file(f)finally:f.close()#always executedprint OK#executed on success onlyRaising Exceptionsraise IndexErrorraise IndexError(k out of range)raise IndexError,k out of rangetry:somethingexcept:#catch everything print Oops raise#reraise和C接口完全兼容f=o
22、pen(,mode,buffersize)mode 可以是r,w,a(like C);default r“b”/”+”buffersize:0=unbuffered;1=line-buffered;bufferedmethods:read(nbytes),readline(),readlines()write(string),writelines(list)seek(pos,how),tell()flush(),close()fileno()Example 替换文本文件内容input=open(“input.txt”)output=open(“output.txt”,“a”)output.wr
23、ite(input.read().replace(“windows”,“linux”)output.close()input.close()获取uin列表input=open(“input.txt”)uins=int(line)for line in input if line.lstrip().rstrip()input.close()Socket和C接口完全兼容sock=socket(family,type,proto)socket.AF_INETsocket.SOCK_STREAMmethods:bind(),listen(),accept()connect(),close()send(
24、),recv(),sendall()Example Socket Serverdef startup():sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)sock.bind(172.25.40.11,443)/tuple here sock.listen(100)print server started up while True:try:conn,addr=sock.accept()print client%s connection accepted%str(addr)t=threading.Thread(target=run_ech
25、o,args=(conn,1)t.start()except:print exception occurred,sys.exc_info()Example Socket Server(2)def read_policy_file():=crossdomain.xml try:f=open()return f.read()finally:f.close()def run_echo(conn,ignored):try:req=conn.recv(1024)if(req.find()!=-1):conn.sendall(read_policy_file()finally:conn.close()Ad
26、vanced Socket Serverclass RequestHandler(SocketServer.BaseRequestHandler):def _init_(self,request,client_address,server):ip,port=client_address SocketServer.BaseRequestHandler._init_(self,request,client_address,server)def handle(self):sock=self.request try:req=sock.recv(1024)if(req.find(policy-)!=-1
27、):sock.sendall(CANNED_RESPONSE)finally:sock.close()def finish(self):passAdvanced Socket Server(2)class Server(SocketServer.ThreadingMixIn,SocketServer.TCPServer):daemon_threads=True allow_reuse_address=True def _init_(self,server_address,request_handler_class):SocketServer.TCPServer._init_(self,serv
28、er_address,request_handler_class)Advanced Socket Server(3)if _name_=_main_:server=Server(172.25.40.11,8999),RequestHandler)try:server.serve_forever()except KeyboardInterrupt:sys.exit(0)Python2.6 4700rpsPython2.4 600rpsMetaClass类似C+的MetaPrograming可以改变类的行为甚至是new一个完全不同的对象出来!Protobuf协议编解码比较高端Binding C/C
29、+Python访问C+C+访问Python参数都需要转成PyObject对象来传递比较高端标准库Core:os,sys,string,getopt,struct,.Regular expressions:re modulePerl-5风格的正则表达式Internet:socket,rfc822,httplib,htmllib,smtplib,.FrameworksTwistedTornadoGeventDjangoTurbo GearsPythonModule import依照sys.pathsys.path.append(“your own library path”)私有成员变量和函数名以
30、_开始只是一个约定常见错误缩进Import动态类型检查“str”+1对list的索引操作-1即size-1True Or FalseFalse evaluationNoneFalsezero of any numeric type,for example,0,0L,0.0,0j.any empty sequence,for example,(),.any empty mapping,for example,.instances of user-defined classes,if the class defines a _nonzero_()or _len_()method,when that method returns the integer zero or bool value False和C+不同的是or和and操作返回的是他的运算对象Flase or“str”ReferencesPython 核心编程Python cookbook