为了不带入过多的累赘,Python 3.0在设计的时候没有考虑向下相容。
为了照顾现有程式,Python 2.6作为一个过渡版本,基本使用了Python 2.x的语法和库,同时考虑了向Python 3.0的迁移,允许使用部分Python 3.0的语法与函数。
除非执行环境无法安装Python 3.0或者程式本身使用了不支援Python 3.0的第三方库。目前不支援Python 3.0的第三方库有Twisted, py2exe, PIL等。
Python 3.0的变化主要在以下几个方面:
print语句没有了,取而代之的是print()函数。 Python 2.6与Python 2.7部分地支持这种形式的print语法。在Python 2.6与Python 2.7里面,以下三种形式是等价的:
print "fish"
print ("fish") #注意print后面有个空格
print("fish") #print()不能带有任何其它参数
然而,Python 2.6实际已经支持新的print()语法:
from __future__ import print_function
print("fish", "panda", sep=', ')
新的str类别表示一个Unicode字串,相当于Python 2.x版本的unicode类别。而位元组序列则用类似b"abc"的语法表示,用bytes类表示,相当于Python 2.x的str类别。
现在两种类别不能再隐式地自动转换,因此在Python 3.x里面"fish"+b"panda"是错误。正确的写法是"fish"+b"panda".decode("utf-8")。 Python 2.6可以自动地将位元组序列识别为Unicode字串,方法是:
from __future__ import unicode_literals
print(repr("fish"))
除法运算符"/"在Python 3.x内总是返回浮点数。而在Python 2.6内会判断被除数与除数是否是整数。如果是整数会返回整数值,相当于整除;浮点数则返回浮点数值。
为了让Python 2.6统一返回浮点数值,可以:
from __future__ import division print(3/2)
result={}
for k, v in d.items():
result[expr1]=expr2
return result
集合推导式(Set Comprehensions) {expr1 for x in stuff}。这个语法等价于:
result = set()
for x in stuff:
result.add(expr1)
return result
def sendMail(from_: str, to: str, title: str, body: str) -> bool:
pass
| 旧的名字 | 新的名字 |
|---|---|
| _winreg | winreg |
| ConfigParser | configparser |
| copy_reg | copyreg |
| Queue | queue |
| SocketServer | socketserver |
| repr | reprlib |