Python2与Python3的比较

python2                          python3
reload(M)---------------->imp.reload(M) (或exec)
apply(f,ps,ks)------------>f(*ps,**ks)
'X'------------------------>repr(X)
X <> Y------------------->X != Y
long---------------------->int
9999L-------------------->9999
D.has_key(K)------------->K in D (或D.get(key) != None)
raw_input---------------->input
old input----------------->eval(input())
xrange-------------------->range
file------------------------>open(以及io模块类)
X.next--------------------->X.__next__,由next(X)调用
X.__getslice__------------->X.__getitem__,传入一个slice对象
X.__setslice__------------->X.__setitem__,传入一个slice对象
reduce-------------------->functool.reduce(或循环代码)
execfile(filename)-------->exec(open(filename).read())
exec open(filename)----->exec(open(filename).read())
0777---------------------->0o777
print x,y------------------->print(x,y)
print >> F,x,y-------------> pri(x,y,file=F)
print x,y,------------------>print(x,y,end='')
u'ccc'---------------------->'ccc'
'bbb' for byte strings----->b'bbb'
raise E,V ------------------>raise E(V)
execpt E,V:---------------->except E as X:
def f((a,b)):---------------->def f(x):(a,b) = x
file.xreadlines------------->for line in file: (or X=iter(file())
D.keys()等----------------->list(D.keys())(字典视图)
map(),range(),etc. -------->list(map()),list(range())
as lists--------------------->内置函数
map(None,...)-------------->zip(或手动代码来补充结果)
X = D.keys();X.sort()  ------>sorted(D) (或list(D.keys()))
cmp(x,y)------------------->(x>y) - (x<y)
X.__cmp__(y)--------------->__lt__、__gt__、__eq__等
X.__nonzero__-------------->X.__bool__
X.__hex__,X.__oct__--------->X.__index__        
排序比较函数--------------->使用key=transform或reverse=True
Dictionary <,>,<=,--------->Compare sorted(D.items())
>=-------------------------->(或循环编码)
types.ListType-------------->list(types只用于非内建名称)
__metaclass__ = M--------->class C(metaclass=M):
__builtin__------------------>builtins(重命名)
Tkinter---------------------->tkinter(重命名)
sys.exc_type、exc_value--->sys.exc_info()[0],[1]
function.func_code-------->function.__code__
由内置函数运行的----------->在包装类中重定义__X__方法
__getattr__
-t,__tt命令行切换------------>不一致地使用制表符/空格总是一个错误
一个函数中的from...*-------->只能够出现在一个文件的顶层
导入模块,在同一包中------->from . import mod,包相关的形式
class MyException:---------->class MyException(Exception):
exceptions module---------->内置作用域,库手册
thread、Queue modules---->_thread,queue
anydbm module------------->dbm(改名了)
cPickle module--------------->_pickle(改名了,自动使用)
os.popen2/3/4--------------->subprocess.Popen(os.popen保留)
给予字符串的异常------------->基于类的异常(python2.6中也是如此)
字符串模块函数--------------->字符串对象方法
未绑定方法-------------------->函数(通过实例调用静态方法)
混合类型比较、排序----------->非数字的混合类型比较是错误的
摘录自《python学习手册第4版》


猜你喜欢

转载自blog.csdn.net/eleven_zou/article/details/80885824