【转】python2与python3的主要区别
摘自:http://www.cnblogs.com/codingmylife/archive/2010/06/06/1752807.html
1.性能?
Py3.0運(yùn)行 pystone benchmark的速度比Py2.5慢30%。Guido認(rèn)為Py3.0有極大的優(yōu)化空間,在字符串和整形操作上可?
以取得很好的優(yōu)化結(jié)果。?
Py3.1性能比Py2.5慢15%,還有很大的提升空間。?
2.編碼?
Py3.X源碼文件默認(rèn)使用utf-8編碼,這就使得以下代碼是合法的:?
??? >>> 中國 = 'china'?
??? >>>print(中國)?
??? china?
3. 語法?
1)去除了<>,全部改用!=?
2)去除``,全部改用repr()?
3)關(guān)鍵詞加入as 和with,還有True,False,None?
4)整型除法返回浮點(diǎn)數(shù),要得到整型結(jié)果,請使用//?
5)加入nonlocal語句。使用noclocal x可以直接指派外圍(非全局)變量?
6)去除print語句,加入print()函數(shù)實現(xiàn)相同的功能。同樣的還有 exec語句,已經(jīng)改為exec()函數(shù)?
?? 例如:?
???? 2.X: print "The answer is", 2*2?
???? 3.X: print("The answer is", 2*2)?
???? 2.X: print x,????????????????????????????? # 使用逗號結(jié)尾禁止換行?
???? 3.X: print(x, end=" ")???????????????????? # 使用空格代替換行?
???? 2.X: print???????????????????????????????? # 輸出新行?
???? 3.X: print()?????????????????????????????? # 輸出新行?
???? 2.X: print >>sys.stderr, "fatal error"?
???? 3.X: print("fatal error", file=sys.stderr)?
???? 2.X: print (x, y)????????????????????????? # 輸出repr((x, y))?
???? 3.X: print((x, y))???????????????????????? # 不同于print(x, y)!?
7)改變了順序操作符的行為,例如x<y,當(dāng)x和y類型不匹配時拋出TypeError而不是返回隨即的 bool值??
8)輸入函數(shù)改變了,刪除了raw_input,用input代替:?
?? 2.X:guess = int(raw_input('Enter an integer : ')) # 讀取鍵盤輸入的方法?
?? 3.X:guess = int(input('Enter an integer : '))
9)去除元組參數(shù)解包。不能def(a, (b, c)):pass這樣定義函數(shù)了?
10)新式的8進(jìn)制字變量,相應(yīng)地修改了oct()函數(shù)。?
?? 2.X的方式如下:?
???? >>> 0666?
???? 438?
???? >>> oct(438)?
???? '0666'?
?? 3.X這樣:?
???? >>> 0666?
???? SyntaxError: invalid token (<pyshell#63>, line 1)?
???? >>> 0o666?
???? 438?
???? >>> oct(438)?
???? '0o666'?
11)增加了 2進(jìn)制字面量和bin()函數(shù)?
??? >>> bin(438)?
??? '0b110110110'?
??? >>> _438 = '0b110110110'?
??? >>> _438?
??? '0b110110110'?
12)擴(kuò)展的可迭代解包。在Py3.X 里,a, b, *rest = seq和 *rest, a = seq都是合法的,只要求兩點(diǎn):rest是list?
對象和seq是可迭代的。?
13)新的super(),可以不再給super()傳參數(shù),?
??? >>> class C(object):?
????????? def __init__(self, a):?
???????????? print('C', a)?
??? >>> class D(C):?
????????? def __init(self, a):?
???????????? super().__init__(a) # 無參數(shù)調(diào)用super()?
??? >>> D(8)?
??? C 8?
??? <__main__.D object at 0x00D7ED90>?
14)新的metaclass語法:?
??? class Foo(*bases, **kwds):?
????? pass?
15)支持class decorator。用法與函數(shù)decorator一樣:?
??? >>> def foo(cls_a):?
????????? def print_func(self):?
???????????? print('Hello, world!')?
????????? cls_a.print = print_func?
????????? return cls_a?
??? >>> @foo?
??? class C(object):?
????? pass?
??? >>> C().print()?
??? Hello, world!?
class decorator可以用來玩玩貍貓換太子的大把戲。更多請參閱PEP 3129?
4. 字符串和字節(jié)串?
1)現(xiàn)在字符串只有str一種類型,但它跟2.x版本的unicode幾乎一樣。
2)關(guān)于字節(jié)串,請參閱“數(shù)據(jù)類型”的第2條目?
5.數(shù)據(jù)類型?
1)Py3.X去除了long類型,現(xiàn)在只有一種整型——int,但它的行為就像2.X版本的long?
2)新增了bytes類型,對應(yīng)于2.X版本的八位串,定義一個bytes字面量的方法如下:?
??? >>> b = b'china'?
??? >>> type(b)?
??? <type 'bytes'>?
str對象和bytes對象可以使用.encode() (str -> bytes) or .decode() (bytes -> str)方法相互轉(zhuǎn)化。?
??? >>> s = b.decode()?
??? >>> s?
??? 'china'?
??? >>> b1 = s.encode()?
??? >>> b1?
??? b'china'?
3)dict的.keys()、.items 和.values()方法返回迭代器,而之前的iterkeys()等函數(shù)都被廢棄。同時去掉的還有?
dict.has_key(),用 in替代它吧?
6.面向?qū)ο?
1)引入抽象基類(Abstraact Base Classes,ABCs)。?
2)容器類和迭代器類被ABCs化,所以cellections模塊里的類型比Py2.5多了很多。?
??? >>> import collections?
??? >>> print('\n'.join(dir(collections)))?
??? Callable?
??? Container?
??? Hashable?
??? ItemsView?
??? Iterable?
??? Iterator?
??? KeysView?
??? Mapping?
??? MappingView?
??? MutableMapping?
??? MutableSequence?
??? MutableSet?
??? NamedTuple?
??? Sequence?
??? Set?
??? Sized?
??? ValuesView?
??? __all__?
??? __builtins__?
??? __doc__?
??? __file__?
??? __name__?
??? _abcoll?
??? _itemgetter?
??? _sys?
??? defaultdict?
??? deque?
另外,數(shù)值類型也被ABCs化。關(guān)于這兩點(diǎn),請參閱 PEP 3119和PEP 3141。?
3)迭代器的next()方法改名為__next__(),并增加內(nèi)置函數(shù)next(),用以調(diào)用迭代器的__next__()方法?
4)增加了@abstractmethod和 @abstractproperty兩個 decorator,編寫抽象方法(屬性)更加方便。?
7.異常?
1)所以異常都從 BaseException繼承,并刪除了StardardError?
2)去除了異常類的序列行為和.message屬性?
3)用 raise Exception(args)代替 raise Exception, args語法?
4)捕獲異常的語法改變,引入了as關(guān)鍵字來標(biāo)識異常實例,在Py2.5中:?
??? >>> try:?
??? ...??? raise NotImplementedError('Error')?
??? ... except NotImplementedError, error:
??? ...??? print error.message?
??? ...?
??? Error?
在Py3.0中:?
??? >>> try:?
????????? raise NotImplementedError('Error')?
??????? except NotImplementedError as error: #注意這個 as?
????????? print(str(error))?
??? Error?
5)異常鏈,因為__context__在3.0a1版本中沒有實現(xiàn)?
8.模塊變動?
1)移除了cPickle模塊,可以使用pickle模塊代替。最終我們將會有一個透明高效的模塊。?
2)移除了imageop模塊?
3)移除了 audiodev, Bastion, bsddb185, exceptions, linuxaudiodev, md5, MimeWriter, mimify, popen2,??
rexec, sets, sha, stringold, strop, sunaudiodev, timing和xmllib模塊?
4)移除了bsddb模塊(單獨(dú)發(fā)布,可以從http://www.jcea.es/programacion/pybsddb.htm獲取)?
5)移除了new模塊?
6)os.tmpnam()和os.tmpfile()函數(shù)被移動到tmpfile模塊下?
7)tokenize模塊現(xiàn)在使用bytes工作。主要的入口點(diǎn)不再是generate_tokens,而是 tokenize.tokenize()?
9.其它?
1)xrange() 改名為range(),要想使用range()獲得一個list,必須顯式調(diào)用:?
??? >>> list(range(10))?
??? [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]?
2)bytes對象不能hash,也不支持 b.lower()、b.strip()和b.split()方法,但對于后兩者可以使用 b.strip(b’??
\n\t\r \f’)和b.split(b’ ‘)來達(dá)到相同目的?
3)zip()、map()和filter()都返回迭代器。而apply()、 callable()、coerce()、 execfile()、reduce()和reload?
()函數(shù)都被去除了
現(xiàn)在可以使用hasattr()來替換 callable(). hasattr()的語法如:hasattr(string, '__name__')
4)string.letters和相關(guān)的.lowercase和.uppercase被去除,請改用string.ascii_letters 等?
5)如果x < y的不能比較,拋出TypeError異常。2.x版本是返回偽隨機(jī)布爾值的?
6)__getslice__系列成員被廢棄。a[i:j]根據(jù)上下文轉(zhuǎn)換為a.__getitem__(slice(I, j))或 __setitem__和?
__delitem__調(diào)用?
7)file類被廢棄,在Py2.5中:?
??? >>> file?
??? <type 'file'>?
在Py3.X中:?
??? >>> file?
??? Traceback (most recent call last):?
??? File "<pyshell#120>", line 1, in <module>?
?????? file?
??? NameError: name 'file' is not defined
總結(jié)
以上是生活随笔為你收集整理的【转】python2与python3的主要区别的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: maven仓库配置和 修改阿里云镜像
- 下一篇: 树莓派GPIO资料