姜太公 写道
原文:What's New in Python 3.0
这篇文章主要介绍了相比于python2.6,python3.0的新特性。更详细的介绍请参见python3.0的文档。
Common Stumbling Blocks
本段简单的列出容易使人出错的变动。
* print语句被print()函数取代了,可以使用关键字参数来替代老的print特殊语法。例如:
1. Old: print "The answer is", 2*2
2. New: print("The answer is", 2*2)
3. Old: print x, # 使用逗号结尾禁止换行
4. New: print(x, end=" ") # 使用空格代替换行
5. Old: print # 输出新行
6. New: print() # 输出新行
7. Old: print >>sys.stderr, "fatal error"
8. New: print("fatal error", file=sys.stderr)
9. Old: print (x, y) # 输出repr((x, y))
10. New: print((x, y)) # 不同于print(x, y)!
你可以自定义输出项之间的分隔符:
print("There are <", 2**32, "> possibilities!", sep="")
输出结果是:
There are <4294967296> possibilities!
注意:
1. print()函数不支持老print语句的“软空格”特性,例如,在python2.x中,print "A\n", "B"会输出"A\nB\n",而python3.0中,print("A\n", "B")会输出"A\n B\n"
2. 学会渐渐习惯print()吧!
3. 使用2to3源码转换工具时,所有的print语句被自动转换成print()函数调用,对大项目,这是无需争论的。
* python3.0使用字符串(strings)和bytes代替Unicode字符串和8位字符串,这意味着几乎所有使用Unicode编码和二进制数据的代码都要改动。这个改动很不错,在2.x的世界里,无数的bug都是因为编码问题。
* map()和filter()返回迭代器(iterators)
* dict方法keys(),items(),values()返回视图(同样是迭代器)而不是列表(list)
* 内建的sorted()方法和list.sort()方法不再接受表示比较函数的cmp参数,使用key参数代替。
* 1/2返回浮点数,使用1//2能得到整数。
* repr()函数对于long整数不再包含拖尾的L,所以不加判断的去除最后一个字符会导致去掉一个有用的数字。
String and Bytes
* 现在只有一种字符串:str,它的行为和实现都很像2.x的unicode串。
* basestring超类已经去掉了,2to3工具会把每个出现的basestring替换成str。
* PEP3137:新类型bytes,用来表示二进制数据和编码文本,str和bytes不能混合,需要时,必须进行显示的转换,转换方法是str.encode()(str->bytes)和bytes.decode()(bytes->str).
* 在原始字符串(raw strings)中所有反斜线都按字面量解释,不再特殊处理Unicode转义字符。
* PEP3112:bytes字面量,例如b"abc",创建bytes实例。
* PEP3120:默认源文件编码为UTF-8
* PEP3131:可以使用非ASCII标识符(然而,除了注释中贡献者的名字之外,标准库仍然只包含ASCII)
* PEP3116:新的IO实现,API几乎100%向后兼容,二进制文件使用bytes代替strings
* 去除了StringIO和cStringIO模块,取而代之的是io.StringIO或者io.BytesIO
PEP3101:字符串格式化的新方法
* str.format方法(原文提到替代了%操作符,实际上,format方法和%的用法差别很大,各有所长)。
PEP3106:修补了dict的keys(),items(),values()方法
* 删除了dict.iterkeys(),dict.itervalues()和dict.iteritems()
* dict.keys(),dict.values()和dict.items()返回dict相关数据的引用
PEP3107:函数注解(Function Annotations)
* 注解函数参数和返回值的标准化方法
Exception Stuff
* PEP352:异常类必须继承自BaseException,它异常结构的基类。
* 移除了StandardError
* Dropping sequence behavior (slicing!) and message attribute of exception instances.
* PEP3109:抛出异常:现在必须使用raise Exception(args)而不是原来的raise Exception, args
* PEP3110:捕获异常,现在必须使用except Exception as identifier而不是原来的except Exception, identifier
* PEP3134:异常链(Exception chain)。
* 改良了一些windows不能加载模式时的异常信息,具有本地化处理。
New Class and Metaclass Stuff
* 移除了classic class
* PEP3115:新的metaclass语法
* PEP3119:抽象基类。
* PEP3129:类包装。
* PEP3141:数字抽象基类
其他的语言变化
这里列出大多数的python语言核心和内建函数的变化。
* 移除了backticks(使用repr()代替)
* 移除了<>(不等号,使用!=代替)
* as和with变成了关键字
* True,False和None变成了关键字
* PEP237:long不存在了,只有int,它和原来的long一样。不再支持以L结尾的数字字面量。移除sys.maxint,因为int现在已经是无限大了
* PEP238:int相除,返回float
* 改变了顺序操作符的行为,例如x<y,当x和y类型不匹配时抛出TypeError而不是返回随即的bool值
* 移除了__getslice__,语法a[i:j]被解释成a.__getitem__(slice(i,j))
* PEP3102:keyword-only arguments.在函数参数列表中,出现在*args之后的命名参数只能使用"关键字参数"的形式调用
* PEP3104:nonlocal声明。使用nonlocal可以声明一个外部变量(不是global变量)
* PEP3111:raw_input()改名为input(),也就是说,新的input()函数从标准输入设备(sys.stdin)读取一行并返回(不包括行结束符),如果输入过早终止,该函数抛出EOFError,如果想使用老的input(),可以使用eval(input())代替。
* xrange()改名为range(),range()现在不是产生一个列表(list),而是一个迭代器。
* PEP3113:移除了"元组参数拆包(tuple parameter unpacking)"。这种写法已经不行了:
def foo(a, (b, c)):...
现在要这样写:
def foo(a, b_c):
b,c = b_c
* PEP3114:next()重命名为__next__(),新的内建函数next()可以调用一个对象的__next__()方法。
* PEP3127:新的八进制字面量,二进制字面量和bin()函数。你应该写0o666而不是0666,oct()函数也做了响应的改动。同样,0b1010等价于10,bin(10)返回"0b1010"。0666这种写法现在是错误的。
* PEP3132:支持迭代器拆包。现在你可以这样写:
a, b, *rest = some_seqence
甚至象这样:
*rest, a = stuff
一般情况下,rest对象是list,而等号右边的对象是可迭代的
* PEP3135:新的super()。你可以不适用任何参数调用super(),正确的参数和实例会被正确选择。如果使用参数,它的行为不变,和以前一样。
* zip(),map(),filter()返回迭代器。
* 移除了string.letters和它的朋友们(string.lowcase和string.uppercase),现在上场的是string.ascii_letters等
* 移除了apply(),callable(),exefile(),file(),reduce(),reload()
* 移除了dict.has_key()。使用in操作符进行测试
* exec语句没有了,现在是exec()函数
* 移除了__oct__()和__hex__()特殊方法。oct()和hex()方法使用__index__()
* 移除了对__members__和__methods__的支持
* nb_nonzero重命名为nb_bool,__nonzero__()重命名为__bool__()
Optimizations
* 一般情况下,python 3.0比python 2.5慢33%左右。不过仍有提升空间。
模块变动(新的,改进的和废弃的)
* 移除了cPickle模块,可以使用pickle模块代替。最终我们将会有一个透明高效的模块。
* 移除了imageop模块
* 移除了audiodev, Bastion, bsddb185, exceptions, linuxaudiodev, md5, MimeWriter, mimify, popen2, rexec, sets, sha, stringold, strop, sunaudiodev, timing和xmllib模块
* 移除了bsddb模块(单独发布,可以从http://www.jcea.es/programacion/pybsddb.htm获取)
* 移除了new模块
* os.tmpnam()和os.tmpfile()函数被移动到tmpfile模块下
* tokenize模块现在使用bytes工作。主要的入口点不再是generate_tokens,而是tokenize.tokenize()
Build and C API Changes
Python’s build process和C API的改动包括:
* PEP3118:新的Buffer API
* PEP3121:扩展模块的的Initialization & Finalization
* PEP3123:使PyObject_HEAD符合标准C
其他的改动和修复
在源码里分散一系列的改进和bug修复。changes log表明,从2.6到3.0,有XXX个改动和YYY的bug修复。
分享到:
相关推荐
What's New in Zigbee 3.0.pdf
spaCy 用户手册,spaCy是我的自然语言处理(NLP)任务的必备库,系列使用手册文档。
OpenMP 3.0 What's new
藏经阁-Apache Hadoop 3.0_ What’s new in YARN & MapReduce.pdf
What’s New in Delphi 7 官方说明,英文
What's New in Java 12 What's New in Java 12 What's New in Java 12
What Is New in MySQL 5.7之新特性篇
What's New in Java 12;What's New in Java 12;What's New in Java 12;What's New in Java 12
What’s New in Java 11?-O’Reilly(2019).pdf 带书签,全彩非 true pdf。
A visual step-by-step guide to writing code in Python. Beginners and experienced programmers can use Python to build and play computer games, from mind-bending brainteasers to crazy action games with ...
What's new in Python 2.6? or all "What's new" documents since 2.0 Tutorial start here Using Python how to use Python on different platforms Language Reference describes syntax and language elements...
Finance in SAP S/4HANA 1909 Michel Haesendonckx, SAP SE September 2019
What's New in PADS 9.0.pdf
What is new in FMI 3.0 The FMI Design Community has improved the FMI standard to react to new requirements from the system simulation community. Especially the ability to package control code into ...
What’s New In Rails 2.1: A Well Produced, Free E-Book
It will teach you how to visualize what’s happening in the model internally. If you want more than just a superficial look at machine learning models, this course is for you. NOTES: All the code ...
牛津小学英语 1BUnit 8What’s in your bag_ Story time 课件+素材.zip
What's New in Oracle Solaris 11.3-40
What's New in Extended Warehouse Management in SAP S_4HANA 1909
So what’s going to be in this course and how will it build on the previous neural network courses and Hidden Markov Models? In the first section of the course we are going to add the concept of time...