本文通過(guò)列舉出一些常見(jiàn)的實(shí)例來(lái)分析Python3.0與2.X版本的區(qū)別,是作者經(jīng)驗(yàn)的總結(jié),對(duì)于Python程序設(shè)計(jì)人員來(lái)說(shuō)有不錯(cuò)的參考價(jià)值。具體如下:
做為一個(gè)前端開(kāi)發(fā)的碼農(nóng),最近通過(guò)閱讀最新版的《A byte of Python》并與老版本的《A byte of Python》做對(duì)比后,發(fā)現(xiàn)Python3.0在某些地方還是有些改變的。之后再查閱官方網(wǎng)站的文檔,總結(jié)出一下區(qū)別:
1. 如果你下載的是最新版的Python,就會(huì)發(fā)現(xiàn)所有書中的Hello World例子將不再正確。
Python2.X代碼如下:
print "Hello World!" #打印字符串
Python3.0代碼如下:
print("Hello World!")
將字符串放到括號(hào)中print出來(lái),這種寫法對(duì)于我這種學(xué)習(xí)Java出身的人來(lái)說(shuō),很是親切啊~O(∩_∩)O~
2.
Python2.X代碼如下:
guess = int(raw_input('Enter an integer : ')) #讀取鍵盤輸入的方法
Python3.0代碼如下:
guess = int(input('Enter an integer : '))
方法名變得更加容易記!
3.
加入了一個(gè)新的nonlocal statement,非局部變量,它的范圍介于global和local之間,主要用于函數(shù)嵌套,用法如下:
#!/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,不知道這個(gè)翻譯成什么比較妥當(dāng)?先看下面這個(gè)例子:
#!/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))
當(dāng)在參數(shù)前面使用*標(biāo)識(shí)的時(shí)候,所有的位置參數(shù)(1,2,3)作為一個(gè)list傳遞。
當(dāng)在參數(shù)前面使用**標(biāo)識(shí)的時(shí)候,所有的關(guān)鍵參數(shù)(vegetables=50, fruits=100)作為一個(gè)dictionary傳遞。
5.
關(guān)于Packages的話題,個(gè)人理解有限。感興趣的讀者可以查閱相關(guān)文檔。
6.
在數(shù)據(jù)結(jié)構(gòu)中,多了一種類型:set
Set是一種無(wú)序的簡(jiǎn)單對(duì)象的集合,當(dāng)我們關(guān)心一個(gè)對(duì)象是否在一個(gè)集合中存在,而順序和出現(xiàn)的次數(shù)是次要的時(shí)候,可以使用set。
7.
關(guān)于os.sep方法,(set是separator,分隔符的縮寫)
來(lái)看看作者的一個(gè)很暈菜的例子:
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的功能是自動(dòng)辨別操作系統(tǒng),給出不同的分隔符,Windows上是\\,Linux上是/,原理是明白了,功能也很不錯(cuò),但是作者的例子。只有一處使用了os.sep,其他的地方還是老的寫法啊(E:\\)
8.
可以使用@修飾符聲明一個(gè)類方法:?
@classmethod def howMany(klass): '''Prints the current population.''' print('We have {0:d} robots.'.format(Robot.population))
9.
可以將以個(gè)類用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')二進(jìn)制文件('b')。
11.將打開(kāi)文件的操作放到使用with語(yǔ)句修飾的方法中,書上說(shuō)好處是讓我們更專注于文件操作,讓代碼看起來(lái)不凌亂,本文還不能完全體會(huì)with的好處。現(xiàn)給出示例代碼供大家參考:
#!/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,給我的感覺(jué)類似于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")
希望本文所述能對(duì)大家理解Python3.0與Python2.X一些區(qū)別性的用法有所幫助。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
