py3.x和py2.x的區(qū)別簡(jiǎn)要分析
這個(gè)星期開(kāi)始學(xué)習(xí)Python了,因?yàn)榭吹臅?shū)都是基于Python2.x,而且我安裝的是Python3.1,所以書(shū)上寫(xiě)的地方好多都不適用于Python3.1,特意在Google上search了一下3.x和2.x的區(qū)別。特此在自己的空間中記錄一下,以備以后查找方便,也可以分享給想學(xué)習(xí)Python的friends.
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編碼,這就使得以下代碼是合法的:
>>> 中國(guó) = 'china'
>>>print(中國(guó))
china
3. 語(yǔ)法
1)去除了<>,全部改用!=
2)去除``,全部改用repr()
3)關(guān)鍵詞加入as 和with,還有True,False,None
4)整型除法返回浮點(diǎn)數(shù),要得到整型結(jié)果,請(qǐng)使用//
5)加入nonlocal語(yǔ)句。使用noclocal x可以直接指派外圍(非全局)變量
6)去除print語(yǔ)句,加入print()函數(shù)實(shí)現(xiàn)相同的功能。同樣的還有 exec語(yǔ)句,已經(jīng)改為exec()函數(shù)
例如:
2.X: print "The answer is", 2*2
3.X: print("The answer is", 2*2)
2.X: print x, # 使用逗號(hào)結(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 8)輸入函數(shù)改變了,刪除了raw_input,用input代替:
2.X:guess = int(raw_input('Enter an integer : ')) # 讀取鍵盤(pán)輸入的方法
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 (, 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
對(duì)象和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) # 無(wú)參數(shù)調(diào)用super()
>>> D(8)
C 8
<__main__.D object at 0x00D7ED90>
14)新的metaclass語(yǔ)法:
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可以用來(lái)玩玩貍貓換太子的大把戲。更多請(qǐng)參閱PEP 3129
4. 字符串和字節(jié)串
1)現(xiàn)在字符串只有str一種類(lèi)型,但它跟2.x版本的unicode幾乎一樣。