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. 語法
- 去除了<>,全部改用!=
- 去除``,全部改用 repr()
- 關(guān)鍵詞加入
as
和with
,還有True
,False
,None
- 整型除法返回浮點(diǎn)數(shù),要得到整型結(jié)果,請使用//
- 加入
nonlocal
語句。使用noclocal x
可以直接指派外圍(非全局)變量 - 去除
print
語句,加入print()
函數(shù)實(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)!
- 改變了順序操作符的行為,例如x<y,當(dāng)x和y類型不匹配時(shí)拋出
TypeError
而不是返回隨即的bool
值 - 輸入函數(shù)改變了,刪除了
raw_input
,用input
代替:
2.X:guess = int(raw_input('Enter an integer : ')) # 讀取鍵盤輸入的方法
3.X:guess = int(input('Enter an integer : '))
- 去除元組參數(shù)解包。不能
def(a, (b, c)):pass
這樣定義函數(shù)了 - 新式的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'
- 增加了 2進(jìn)制字面量和
bin()
函數(shù)
>>> bin(438)
'0b110110110'
>>> _438 = '0b110110110'
>>> _438
'0b110110110'
- 擴(kuò)展的可迭代解包。在Py3.X 里,
a, b, *rest = seq
和*rest, a = seq
都是合法的,只要求兩點(diǎn):rest是list
對象和seq是可迭代的。 - 新的
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>
- 新的metaclass語法:
class Foo(*bases, **kwds):
pass
- 支持
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!
四、字符串和字節(jié)串
- 現(xiàn)在字符串只有str一種類型,但它跟2.x版本的unicode幾乎一樣。
- 關(guān)于字節(jié)串,請參閱“數(shù)據(jù)類型”的第2條目
五、數(shù)據(jù)類型
- Py3.X去除了long類型,現(xiàn)在只有一種整型——int,但它的行為就像2.X版本的long
- 新增了bytes類型,對應(yīng)于2.X版本的八位串,定義一個(gè)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'
- dict的
.keys()
、.items
和.values()
方法返回迭代器,而之前的iterkeys()
等函數(shù)都被廢棄。同時(shí)去掉的還有
dict.has_key()
,用in
替代它
六.面向?qū)ο?/h3>
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
- 迭代器的
next()
方法改名為__next__()
,并增加內(nèi)置函數(shù)next()
,用以調(diào)用迭代器的__next__()
方法 - 增加了
@abstractmethod
和@abstractproperty
兩個(gè) decorator,編寫抽象方法(屬性)更加方便。
七.異常
- 所以異常都從
BaseException
繼承,并刪除了StardardError
- 去除了異常類的序列行為和
.message
屬性 - 用
raise Exception(args)
代替raise Exception
,args
語法 - 捕獲異常的語法改變,引入了as關(guān)鍵字來標(biāo)識異常實(shí)例,在Py2.5中:
>>> try:
... raise NotImplementedError('Error')
... except NotImplementedError, error:
... print error.message
...
Error
在Py3.0中:
>>> try:
raise NotImplementedError('Error')
except NotImplementedError as error: #注意這個(gè) as
print(str(error))
Error
八.模塊變動(dòng)
- 移除了
cPickle
模塊,可以使用pickle
模塊代替。最終我們將會有一個(gè)透明高效的模塊。 - 移除了
imageop
模塊 - 移除了
audiodev
,Bastion
,bsddb185
,exceptions
,linuxaudiodev
,md5
,MimeWriter
,mimify
,popen2
,
rexec
,sets
,sha
,stringold
,strop
,sunaudiodev
,timing
和xmllib
模塊 - 移除了
bsddb
模塊(單獨(dú)發(fā)布,可以從http://www.jcea.es/programacion/pybsddb.htm獲取) - 移除了
new
模塊 -
os.tmpnam()
和os.tmpfile()
函數(shù)被移動(dòng)到tmpfile
模塊下 -
tokenize
模塊現(xiàn)在使用bytes
工作。主要的入口點(diǎn)不再是generate_tokens
,而是tokenize.tokenize()
九.其它
-
xrange()
改名為range()
,要想使用range()
獲得一個(gè)list,必須顯式調(diào)用:
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
bytes對象不能hash,也不支持
b.lower()
、b.strip()
和b.split()
方法,但對于后兩者可以使用b.strip(b’ \n\t\r \f’)
和b.split(b’ ‘)
來達(dá)到相同目的zip()
、map()
和filter()
都返回迭代器。而apply()
、callable()
、coerce()
、execfile()
、reduce()
和reload ()
函數(shù)都被去除了
現(xiàn)在可以使用hasattr()
來替換callable(). hasattr()
的語法如:hasattr(string, '__name__')
string.letters
和相關(guān)的.lowercase
和.uppercase
被去除,請改用string.ascii_letters
等如果x < y的不能比較,拋出TypeError異常。2.x版本是返回偽隨機(jī)布爾值的
__getslice__
系列成員被廢棄。a[i:j]
根據(jù)上下文轉(zhuǎn)換為a.__getitem__(slice(I, j))
或__setitem__
和
__delitem__
調(diào)用-
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
**Python2.4+ 與 Python3.0+ 主要變化或新增內(nèi)容**
```python
Python2 Python3
print是內(nèi)置命令 print變?yōu)楹瘮?shù)
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()方法調(diào)用
x.__getslice__() x.__getitem__()
x.__setsilce__() x.__setitem__()
__cmp__() 刪除了__cmp__(),改用__lt__(),__gt__(),__eq__()等
reduce() functools.reduce()
exefile(filename) exec(open(filename).read())
0567 0o567 (八進(jìn)制)
新增nonlocal關(guān)鍵字
str用于Unicode文本,bytes用于二進(jìn)制文本
新的迭代器方法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參數(shù)
增加Ellipse對象
簡化了super()方法語法
用過-t,-tt控制縮進(jìn) 混用空格與制表符視為錯(cuò)誤
from M import *可以 只能出現(xiàn)在文件的頂層
出現(xiàn)在任何位置.
class MyException: class MyException(Exception):
thread,Queue模塊 改名_thread,queue
cPickle,SocketServer模塊 改名_pickle,socketserver
ConfigSparser模塊 改名configsparser
Tkinter模塊 改名tkinter
其他模塊整合到了如http模塊,urllib, urllib2模塊等
os.popen subprocess.Popen
基于字符串的異常 基于類的異常
新增類的property機(jī)制(類特性)
未綁定方法 都是函數(shù)
混合類型可比較排序 非數(shù)字混合類型比較發(fā)生錯(cuò)誤
/是傳統(tǒng)除法 取消了傳統(tǒng)除法, /變?yōu)檎娉?無函數(shù)注解 有函數(shù)注解 def f(a:100, b:str)->int 使用通過f.__annotation__
新增環(huán)境管理器with/as
Python3.1支持多個(gè)環(huán)境管理器項(xiàng) with A() as a, B() as b
擴(kuò)展的序列解包 a, *b = seq
統(tǒng)一所有類為新式類
增強(qiáng)__slot__類屬性
if X: 優(yōu)先X.__len__() 優(yōu)先X.__bool__()
type(I)區(qū)分類和類型 不再區(qū)分(不再區(qū)分新式類與經(jīng)典類,同時(shí)擴(kuò)展了元類)
靜態(tài)方法需要self參數(shù) 靜態(tài)方法根據(jù)聲明直接使用
無異常鏈 有異常鏈 raise exception from other_exception
有什么需要隨時(shí)聯(lián)系小編??很愿意效勞
image