`
jythoner
  • 浏览: 602472 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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")

6
0
分享到:
评论
3 楼 xredman 2010-10-12  
tangfeng 写道
Python3.0和2.X是有很多差别的!有一个PPT将的很清楚,目前我们都还在用2.5

有那个ppt,可以不可以share一下?
2 楼 fkpwolf 2009-01-19  
nice a
1 楼 tangfeng 2008-12-10  
Python3.0和2.X是有很多差别的!有一个PPT将的很清楚,目前我们都还在用2.5

相关推荐

    A Byte of Python v1.92 (for Python 3.0).rar

    On the same note, if you're wondering whether to learn Python 2.x or 3.x, then read this article by James Bennett [6]. Python是一种简单易学,功能强大的编程语言,它有高效率的高层数据结构,简单而...

    HTMLTestRunner3.0.rar

    python自动化测试报告,存在在python安装目录的lib下面,本文档适用于python3.0以上,文件名HTMLTestRunner.py

    Python3.0与2.X版本的区别实例分析

    本文通过列举出一些常见的实例来分析Python3.0与2.X版本的区别,是作者经验的总结,对于Python程序设计人员来说有不错的参考价值。具体如下: 做为一个前端开发的码农,最近通过阅读最新版的《A byte of Python》并...

    深入浅析Python2.x和3.x版本的主要区别

    Python 2.6作为一个过渡版本,基本使用了Python 2.x的语法和库,同时考虑了向Python 3.0的迁移,允许使用部分Python 3.0的语法与函数。   除非为了使用旧的Python2.x项目代码或只支持2.x的第三方库,否则不推荐使用...

    Python2.x与3.x版本有哪些区别

    为了照顾现有程式,Python 2.6作为一个过渡版本,基本使用了Python 2.x的语法和库,同时考虑了向Python 3.0的迁移,允许使用部分Python 3.0的语法与函数。 新的Python程式建议使用Python 3.0版本的语法。 除非执行...

    byte_of_python_v192.pdf

    Introduction 'A Byte of Python' is a book on programming using the Python language...the same note, if you're wondering whether to learn Python 2.x or 3.x, then read this article by James Bennett [6] .

    python-2.7.18.amd64.msi

    python 2.x系列最后一个版本,2.x系列确认不再更新,以后都3.0以上的啦,各位可以收藏下,做个纪念。 官网:https://www.python.org/ 下载网址:https://www.python.org/ftp/python/2.7.18/python-2.7.18.amd64.msi

    Python2.x与Python3.x的区别

    为了照顾现有程式,Python 2.6作为一个过渡版本,基本使用了Python 2.x的语法和库,同时考虑了向Python 3.0的迁移,允许使用部分Python 3.0的语法与函数。 新的Python程式建议使用Python 3.0版本的语法。 除非执行...

    Python2.x与3​​.x版本区别

    Python2.x与3​​.x版本区别 Python的3​​.0版本,常被称为Python 3000,或简称Py3k。相对于Python的早期版本,这是一个较大的升级。 为了不带入过多的累赘,Python 3.0在设计的时候没有考虑向下相容。 许多针对...

    Python详细入门练习(1).doc

    已知a = 6,b = -4,则Python表达式 a / 2 + b % 2 * 3 的值为() A.3 B.3.0 C.5 D.5.0 7.下列哪个语句在Python中是非法的?( ) A.x = y = z = 1 B.x = (y = z + 1) C.x, y = y, x D.x += y 8.我们学习...

    Python详细入门练习.doc

    已知a = 6,b = -4,则Python表达式 a / 2 + b % 2 * 3 的值为() A.3 B.3.0 C.5 D.5.0 7.下列哪个语句在Python中是非法的?( ) A.x = y = z = 1 B.x = (y = z + 1) C.x, y = y, x D.x += y 8.我们学习...

    编程(完整版)Python题库word练习.doc

    运行下列 Python程序,结果正确的是( ) a=32 b=14 c=a%b print(c) A.2 B.4 C.32 D.14 2.下列python表达式结果最小的是( ) A.2**3//3+8%2*3 B.5**2%3+7%2**2 C.1314//100%10 D.int("1"+"5")//3 3.下列...

    [论坛社区]MyPHP Forum 3.0 Final_forum3.rar

    资源内容:项目全套源码+完整文档 源码说明: 全部项目源码都是经过测试校正后百分百成功运行。 SpringBoot 毕业设计,SpringBoot 课程...部署环境:Tomcat(建议用 7.x 或者 8.x b版本),maven Spring root vue.js

    【英文原版】笨办法学Python3(真正Python3.0文字版)(Learn Python 3 the Hard Way)

    ★☆★“人生苦短,我看原版”系列 ★☆★ 这是英文原版《笨办法学Python 3》,真正的基于Python 3.6,网上很多骗人的说是第三版第四版,都其实是基于Python 2.x 。 虽然是英文版,但是语法用词都不难。实在不行还有...

    dll2lib.rar (需要安装 python2.X )

    因为是 python 写的,所以需要下载 python (目前为 2.7 ,不要使用 3.X 版的,因为 3.X 版认为 print "string" 是语法错误的) ------------------- 传说中的分隔线 ------------------- 你可能对下面的内容也感...

    资料(完整版)python真题练习.doc

    资料(完整版)python真题练习 一、选择题 1.在python中运行print("3+6")的结果是( ...已知a = 6,b = -4,则Python表达式 a / 2 + b % 2 * 3 的值为() A.3 B.3.0 C.5 D.5.0 8.关于python程序设计语言,下列说法

    全国计算机等级考试二级Python真题及解析(9)精品练习.doc

    在Python中,表达式(21%4)+5的值是( ) A.2 B.6 C.10 D.3 5.在Python中,表达式(21%4)+3的值是( ) A.2 B.4 C.6 D.8 6.下列哪个语句在Python中是非法的?( ) A.x = y = z = 1 B.x = (y = z + 1) C...

    Python Pocket Reference 2009 (epub 格式)

    This fourth edition covers both Python versions 3.0 and 2.6, and later releases in the 3.X and 2.X lines. This edition is focused primarily on Python 3.0, but also documents differences in Python 2.6,...

    mysql_python

    在windows环境下好像无法直接pip install, 用于python2.x的mysql扩展

    批量梯度下降法python具体实现

    y = x * 3.0 + 4.0 + np.random.normal(size = 100) X = x.reshape(-1, 1) #损失函数 def J(theta, X_b, y): try: return np.sum((y - X_b.dot(theta))**2)/len(X_b) except: return float('inf') #损失函数的...

Global site tag (gtag.js) - Google Analytics