[翻譯] Google 建議的 Python 風格指南 28,29

看板Python作者 (沒回應=掛站)時間12年前 (2013/05/14 12:05), 編輯推噓5(502)
留言7則, 6人參與, 最新討論串1/1
原文網址:http://google-styleguide.googlecode.com/svn/trunk/pyguide.html * 類別 若沒有繼承自其他類別,則一個類別應明確寫出繼承自 object 類別。即使是嵌入 類別 (nested class) 也應遵守。 Yes: class SampleClass(object): pass class OuterClass(object): class InnerClass(object): pass class ChildClass(ParentClass): """Explicitly inherits from another class already.""" No: class SampleClass: pass class OuterClass: class InnerClass: pass 繼承自 object 能確保 property 正常作用,並確保程式能與 Python 3000 (編案 :即 Python 3.0) 並容。某些能讀取類別意義的方法也能繼承自 object,包括: __new__, __init__, __delattr__, __getattribute__, __setattr__, __hash__, __repr__, and __str__。 * 字串 用 % 運算符號來格式化字串,即使參數全是字串也應如此。然而,你應聰明地判斷 使用 + 與 % 的時機。 Yes: x = a + b x = '%s, %s!' % (imperative, expletive) x = 'name: %s; score: %d' % (name, n) No: x = '%s%s' % (a, b) # use + in this case x = imperative + ', ' + expletive + '!' x = 'name: ' + name + '; score: ' + str(n) 在迴圈中避免使用 + 及 += 來組成字串,這是因為字串是不可變的物件,因此在操 作的過程中需要創造很多非必要的暫時物件,並導致二次方而非線性的執行時間。 你應該用把每個子字串當作 list 並把 list 加在一起,迴圈結束後再用 ''.join 來轉換成完整的字串 (或者,把每個子字串寫入 cStringIO.StringIO 暫存中)。 Yes: items = ['<table>'] for last_name, first_name in employee_list: items.append('<tr><td>%s, %s</td></tr>' % (last_name, first_name)) items.append('</table>') employee_table = ''.join(items) No: employee_table = '<table>' for last_name, first_name in employee_list: employee_table += '<tr><td>%s, %s</td></tr>' % (last_name, first_name) employee_table += '</table>' 多行的字串用 """ 而非 '''。另外,使用隱性的多行連接會使程式更清楚,因為多 行的字串的縮排方式與其他地方常常不一致。 Yes: print ("This is much nicer.\n" "Do it this way.\n") No: print """This is pretty ugly. Don't do this. """ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 68.232.121.105 ※ 編輯: sandwichC 來自: 68.232.121.105 (05/14 20:07)

05/14 21:29, , 1F
好奇一下 現在%和format 哪個應用上會比較推薦?
05/14 21:29, 1F

05/14 21:55, , 2F
如果你一定只會用到 2.7 和 3 的話 format 通常比較好
05/14 21:55, 2F

05/14 22:34, , 3F
format 功能強太多了 http://ppt.cc/9T-e
05/14 22:34, 3F

05/14 23:10, , 4F
Format好用
05/14 23:10, 4F

05/15 02:03, , 5F
推~ 現在都用format來寫了 XD
05/15 02:03, 5F

05/15 12:39, , 6F
format 的確好用,但 % 比較通用
05/15 12:39, 6F

05/24 01:51, , 7F
感謝樓上幾位的回覆
05/24 01:51, 7F
文章代碼(AID): #1HaYY8IM (Python)