做為一個前端開發的碼農,卻正在閱讀最新版的《A byte of Python》。發現Python3.0在某些地方還是有些改變的。準備慢慢的體會,與老版本的《A byte of Python》做對比,最后再去查閱官方網站的文檔。 
1. 
如果你下載的是最新版的Python,就會發現所有書中的Hello World例子將不再正確。 
Old: 
New: 
print("Hello World!") 
將字符串放到括號中print出來,這種寫法對于我這種學習java出身的人來說,很是親切?。海?nbsp;
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') + '.zNew: 
target_dir = 'E://Backup' 
target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip' 
os.sep的功能是自動辨別操作系統,給出不同的分隔符,Windows上是//,linux上是/,原理我是明白了,功能也很不錯,但是作者的例子。。。。只有一處使用了os.sep,其他的地方還是老的寫法?。‥://) 
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")
新聞熱點
疑難解答