Python 2.x 與 Python3.x 主要區別對照表

jopen 11年前發布 | 19K 次閱讀 Python Python開發

Python2.4+ 與 Python3.0+ 主要變化或新增內容

Python2                 Python3
print是內置命令           print變為函數
print >> f,x,y          print(x,y,file=f)
print x,                print(x,end='')
reload(M)               imp.reload(M)
apply(f, ps, ks)        f(ps, **ks)
x <> y                  x != y
long                    int
1234L                   1234
d.has_key(k)            k in d 或 d.get(k) != None (has_key已死, in永生!!)
raw_input()             input()
input()                 eval(input())
xrange(a,b)             range(a,b)
file()                  open()
x.next()                x.next() 且由next()方法調用
x.getslice()        x.getitem()
x.setsilce()        x.setitem()
cmp()               刪除了cmp(),改用lt(),gt(),eq()等
reduce()                functools.reduce()
exefile(filename)       exec(open(filename).read())
0567                    0o567 (八進制)
                        新增nonlocal關鍵字
                        str用于Unicode文本,bytes用于二進制文本
                        新的迭代器方法range,map,zip等
                        新增集合解析與字典解析
u'unicodestr'           'unicodestr'
raise E,V               raise E(V)
except E , x:           except E as x:
file.xreadlines         for line in file: (or X = iter(file))
d.keys(),d.items(),etc  list(d.keys()),list(d.items()),list(etc)
map(),zip(),etc         list(map()),list(zip()),list(etc)
x=d.keys(); x.sort()    sorted(d)
x.nonzero()         x.bool()
x.hex,x.bin     x.index
types.ListType          list
metaclass = M       class C(metaclass = M):
builtin             builtins
sys.exc_type,etc        sys.exc_info()[0],sys.exc_info()[1],...
function.func_code      function.code
                        增加Keyword-One參數
                        增加Ellipse對象
                        簡化了super()方法語法
用過-t,-tt控制縮進        混用空格與制表符視為錯誤
from M import
可以      只能出現在文件的頂層
出現在任何位置.
class MyException:      class MyException(Exception):
thread,Queue模塊         改名_thread,queue
cPickle,SocketServer模塊</span> 改名_pickle,socketserver
ConfigSparser模塊        改名configsparser
Tkinter模塊</span>              改名</span>tkinter</span></span>
                        其他模塊整合到了如http模塊,urllib, urllib2模塊等
os.popen                subprocess.Popen
基于字符串的異常           基于類的異常
未綁定方法                都是函數
混合類型可比較排序         非數字混合類型比較發生錯誤
/是傳統除法               取消了傳統除法, /變為真除法
無函數注解                有函數注解 def f(a:100, b:str)->int 使用通過f.annotation
                        新增環境管理器with/as
                        Python3.1支持多個環境管理器項 with A() as a, B() as b
                        擴展的序列解包 a, *b = seq
                        統一所有類為新式類
                        增強slot類屬性
if X: 優先X.len()    優先X.bool()
type(I)區分類和類型       不再區分(不再區分新式類與經典類,同時擴展了元類)
靜態方法需要self參數       靜態方法根據聲明直接使用
無異常鏈                  有異常鏈 raise exception from other_exception</span></span>


來自:http://blog.csdn.net/hexrain/article/details/16369933

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!