search
HomeBackend DevelopmentPython TutorialPython3.0与2.X版本的区别实例分析

本文通过列举出一些常见的实例来分析Python3.0与2.X版本的区别,是作者经验的总结,对于Python程序设计人员来说有不错的参考价值。具体如下:

做为一个前端开发的码农,最近通过阅读最新版的《A byte of Python》并与老版本的《A byte of Python》做对比后,发现Python3.0在某些地方还是有些改变的。之后再查阅官方网站的文档,总结出一下区别:

1. 如果你下载的是最新版的Python,就会发现所有书中的Hello World例子将不再正确。
Python2.X代码如下:

print "Hello World!" #打印字符串 

Python3.0代码如下:

print("Hello World!") 

将字符串放到括号中print出来,这种写法对于我这种学习Java出身的人来说,很是亲切啊~O(∩_∩)O~

2.
Python2.X代码如下:

guess = int(raw_input('Enter an integer : ')) #读取键盘输入的方法 

Python3.0代码如下:

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,分隔符的缩写)
来看看作者的一个很晕菜的例子:
Python2.X代码如下:

target_dir = '/mnt/e/backup/' 
target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip' 

Python3.0代码如下:

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一些区别性的用法有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Why are arrays generally more memory-efficient than lists for storing numerical data?Why are arrays generally more memory-efficient than lists for storing numerical data?May 05, 2025 am 12:15 AM

Arraysaregenerallymorememory-efficientthanlistsforstoringnumericaldataduetotheirfixed-sizenatureanddirectmemoryaccess.1)Arraysstoreelementsinacontiguousblock,reducingoverheadfrompointersormetadata.2)Lists,oftenimplementedasdynamicarraysorlinkedstruct

How can you convert a Python list to a Python array?How can you convert a Python list to a Python array?May 05, 2025 am 12:10 AM

ToconvertaPythonlisttoanarray,usethearraymodule:1)Importthearraymodule,2)Createalist,3)Usearray(typecode,list)toconvertit,specifyingthetypecodelike'i'forintegers.Thisconversionoptimizesmemoryusageforhomogeneousdata,enhancingperformanceinnumericalcomp

Can you store different data types in the same Python list? Give an example.Can you store different data types in the same Python list? Give an example.May 05, 2025 am 12:10 AM

Python lists can store different types of data. The example list contains integers, strings, floating point numbers, booleans, nested lists, and dictionaries. List flexibility is valuable in data processing and prototyping, but it needs to be used with caution to ensure the readability and maintainability of the code.

What is the difference between arrays and lists in Python?What is the difference between arrays and lists in Python?May 05, 2025 am 12:06 AM

Pythondoesnothavebuilt-inarrays;usethearraymoduleformemory-efficienthomogeneousdatastorage,whilelistsareversatileformixeddatatypes.Arraysareefficientforlargedatasetsofthesametype,whereaslistsofferflexibilityandareeasiertouseformixedorsmallerdatasets.

What module is commonly used to create arrays in Python?What module is commonly used to create arrays in Python?May 05, 2025 am 12:02 AM

ThemostcommonlyusedmoduleforcreatingarraysinPythonisnumpy.1)Numpyprovidesefficienttoolsforarrayoperations,idealfornumericaldata.2)Arrayscanbecreatedusingnp.array()for1Dand2Dstructures.3)Numpyexcelsinelement-wiseoperationsandcomplexcalculationslikemea

How do you append elements to a Python list?How do you append elements to a Python list?May 04, 2025 am 12:17 AM

ToappendelementstoaPythonlist,usetheappend()methodforsingleelements,extend()formultipleelements,andinsert()forspecificpositions.1)Useappend()foraddingoneelementattheend.2)Useextend()toaddmultipleelementsefficiently.3)Useinsert()toaddanelementataspeci

How do you create a Python list? Give an example.How do you create a Python list? Give an example.May 04, 2025 am 12:16 AM

TocreateaPythonlist,usesquarebrackets[]andseparateitemswithcommas.1)Listsaredynamicandcanholdmixeddatatypes.2)Useappend(),remove(),andslicingformanipulation.3)Listcomprehensionsareefficientforcreatinglists.4)Becautiouswithlistreferences;usecopy()orsl

Discuss real-world use cases where efficient storage and processing of numerical data are critical.Discuss real-world use cases where efficient storage and processing of numerical data are critical.May 04, 2025 am 12:11 AM

In the fields of finance, scientific research, medical care and AI, it is crucial to efficiently store and process numerical data. 1) In finance, using memory mapped files and NumPy libraries can significantly improve data processing speed. 2) In the field of scientific research, HDF5 files are optimized for data storage and retrieval. 3) In medical care, database optimization technologies such as indexing and partitioning improve data query performance. 4) In AI, data sharding and distributed training accelerate model training. System performance and scalability can be significantly improved by choosing the right tools and technologies and weighing trade-offs between storage and processing speeds.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),