Python3.0与Python2.X的区别

正在阅读最新版的《A byte of Python》。发现Python3.0在某些地方还是有些改变的。准备慢慢的体会,与老版本的《A byte of Python》做对比,最后再去查阅官方网站的文档。

1. 
如果你下载的是最新版的Python,就会发现所有书中的Hello World例子将不再正确。 
Old: 
print "Hello World!" #打印字符串 
New: 
print("Hello World!") 
将字符串放到括号中print出来,这种写法对于我这种学习Java出身的人来说,很是亲切啊:)

2. 
Old: 
guess = int(raw_input(‘Enter an integer : ‘)) #读取键盘输入的方法 
New: 
guess = int(input(‘Enter an integer : ‘)) 
方法名变得更加容易记!

3. 
加入了一个新的nonlocal statement,非局部变量,它的范围介于global和local之间,主要用于函数嵌套,用法如下: 
#!/usr/bin/python 
# Filename: func_nonlocal.py

def func_outer(): 
    x = 2 
    print(‘x is‘, x) 
    def func_inner(): 
        nonlocal x 
        x = 5 
    func_inner() 
    print(‘Changed local x to‘, x) 
func_outer()

4. 
VarArgs parameters,不知道这个翻译成什么比较妥当?先看例子: 
#!/usr/bin/python 
# Filename: total.py 
def total(initial=5, *numbers, **keywords): 
    count = initial 
    for number in numbers: 
        count += number 
    for key in keywords: 
        count += keywords[key] 
    return count 
print(total(10, 1, 2, 3, vegetables=50, fruits=100))

当在参数前面使用*标识的时候,所有的位置参数(1,2,3)作为一个list传递。 
当在参数前面使用**标识的时候,所有的关键参数(vegetables=50, fruits=100)作为一个dictionary传递。

5. 
关于Packages的话题,我没看懂。。。哪位大虾帮忙讲解下?

6. 
在数据结构中,多了一种类型:set 
Set是一种无序的简单对象的集合,当我们关心一个对象是否在一个集合中存在,而顺序和出现的次数是次要的时候,可以使用set。

7. 
关于os.sep方法,(set是separator,分隔符的缩写) 
作者的一个很晕菜的例子: 
Old: 
target_dir = ‘/mnt/e/backup/‘ 
target = target_dir + time.strftime(‘%Y%m%d%H%M%S‘) + ‘.zip‘ 
New: 
target_dir = ‘E:\\Backup‘ 
target = target_dir + os.sep + time.strftime(‘%Y%m%d%H%M%S‘) + ‘.zip‘ 
os.sep的功能是自动辨别操作系统,给出不同的分隔符,Windows上是\\,Linux上是/,原理我是明白了,功能也很不错,但是作者的例子。。。。只有一处使用了os.sep,其他的地方还是老的写法啊(E:\\)

8. 
可以使用@修饰符声明一个类方法: 
    @classmethod 
    def howMany(klass): 
        ‘‘‘Prints the current population.‘‘‘ 
        print(‘We have {0:d} robots.‘.format(Robot.population))

9. 
可以将以个类用Metaclasses的方式声明为抽象类抽象方法 
from abc import *

class SchoolMember(metaclass=ABCMeta): 
    ‘‘‘Represents any school member.‘‘‘ 
    def __init__(self, name, age): 
        self.name = name 
        self.age = age 
        print(‘(Initialized SchoolMember: {0})‘.format(self.name))

@abstractmethod 
    def tell(self): 
        ‘‘‘Tell my details.‘‘‘ 
print(‘Name:"{0}" Age:"{1}"‘.format(self.name, self.age), end=" ") 
        #pass

10. 
文件读写的模式又增加了两种:文本本件(‘t‘)二进制文件(‘b‘)。

11.将打开文件的操作放到使用with语句修饰的方法中,书上说好处是让我们更专注于文件操作,让代码看起来不凌乱,我一时间还不能体会with的好处,希望大家指点。 
#!/usr/bin/python 
# Filename: using_with.py 
from contextlib import context 
@contextmanager 
def opened(filename, mode="r") 
    f = open(filename, mode) 
    try: 
        yield f 
    finally: 
        f.close()

with opened("poem.txt") as f: 
    for line in f: 
        print(line, end=‘‘)

12.python3.0中添加了logging module,给我的感觉类似于Java中的log4j,直接看代码: 
import os, platform, logging 
if platform.platform().startswith(‘Windows‘): 
logging_file = os.path.join(os.getenv(‘HOMEDRIVE‘), 
os.getenv(‘HOMEPATH‘), ‘test.log‘) 
else: 
    logging_file = os.path.join(os.getenv(‘HOME‘), ‘test.log‘) 
logging.basicConfig( 
    level=logging.DEBUG, 
    format=‘%(asctime)s : %(levelname)s : %(message)s‘, 
    filename = logging_file, 
    filemode = ‘w‘, 

logging.debug("Start of the program") 
logging.info("Doing something") 
logging.warning("Dying now")

Python3.0与Python2.X的区别

时间: 2024-08-06 23:23:18

Python3.0与Python2.X的区别的相关文章

<转>Python3.x和Python2.x的区别介绍

1.性能Py3.0运行 pystone benchmark的速度比Py2.5慢30%.Guido认为Py3.0有极大的优化空间,在字符串和整形操作上可以取得很好的优化结果.Py3.1性能比Py2.5慢15%,还有很大的提升空间. 2.编码Py3.X源码文件默认使用utf-8编码,这就使得以下代码是合法的:>>> 中国 = 'china'>>>print(中国)china 3. 语法1)去除了<>,全部改用!=2)去除``,全部改用repr()3)关键词加入a

【转】Python3.x和Python2.x的区别

这个星期开始学习Python了,因为看的书都是基于Python2.x,而且我安装的是Python3.1,所以书上写的地方好多都不适用于Python3.1,特意在Google上search了一下3.x和2.x的区别.特此在自己的空间中记录一下,以备以后查找方便,也可以分享给想学习Python的friends. 1.性能 Py3.0运行 pystone benchmark的速度比Py2.5慢30%.Guido认为Py3.0有极大的优化空间,在字符串和整形操作上可 以取得很好的优化结果. Py3.1性

[转载]Python3.x和Python2.x的区别

[转载地址:http://www.cnblogs.com/codingmylife/archive/2010/06/06/1752807.html] 这个星期开始学习Python了,因为看的书都是基于Python2.x,而且我安装的是Python3.1,所以书上写的地方好多都不适用于Python3.1,特意在Google上search了一下3.x和2.x的区别.特此在自己的空间中记录一下,以备以后查找方便,也可以分享给想学习Python的friends. 1.性能 Py3.0运行 pystone

Python3.x和Python2.x的区别(转存参考)

http://www.360doc.com/content/14/0619/23/16740871_388198818.shtml 这个星期开始学习Python了,因为看的书都是基于Python2.x,而且我安装的是Python3.1,所以书上写的地方好多都不适用于Python3.1,特意在Google上search了一下3.x和2.x的区别.特此在自己的空间中记录一下,以备以后查找方便,也可以分享给想学习Python的friends. 1.性能 Py3.0运行 pystone benchmar

Python3.X与Python2.x的区别。

一张图说明Python2.x与Python3.x的不同. Python3.x默认使用Unicode编码.支持中文. 更多介绍请看:https://segmentfault.com/a/1190000000618286#Sections

python3.x与python2.x的区别(转)

转自:http://www.cnblogs.com/codingmylife/archive/2010/06/06/1752807.html 1.性能 Py3.0运行 pystone benchmark的速度比Py2.5慢30%.Guido认为Py3.0有极大的优化空间,在字符串和整形操作上可 以取得很好的优化结果. Py3.1性能比Py2.5慢15%,还有很大的提升空间. 2.编码 Py3.X源码文件默认使用utf-8编码,这就使得以下代码是合法的:     >>> 中国 = 'chi

Python3.x和Python2.x的区别

%5BjavaSE%5D%20%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%BA%8C%E5%8F%89%E6%9F%A5%E6%89%BE%E6%A0%91-%E6%8F%92%E5%85%A5%E8%8A%82%E7%82%B9 ????YTNd8Eto?????????? http://auto.315che.com/lanbojinihuracan/qa23979627-2.htm http://auto.315che.com/bb/qa23924950

python2.0 和python3.0区别

python2.0 和python3.0区别 1.官方解释:    python2.0是过去的遗产:      python3.0是未来使用的.  (去繁从简) 2.语法区别:    python2.0    print "hello"    python3.0    print ("hello")    3.编码不同:    python2.0    不能直接写中文:必须先声明utf-8  如:#-*- coding:utf-8 -*-    python3.0

day10 Python作用域 Python2.7与Python3.x的类继承的区别及其他

一.Python作用域   1.Python中无块级作用域 if 1 == 1: name = 'test' print(name) #输出会报错,因为name的作用域仅限于if下的代码块,而不属于全局   2.Python中以函数为作用域 def func(): func_name = 'func_test' print(func_name) #这里同样会报错,因为变量func_name的作用于func函数中   3.Python作用域链,层层嵌套,使用时从内向外找   4.Python的作用