※ [本文轉錄自 Python 看板 #1HaYY8IM ]
作者: sandwichC (沒回應=掛站) 看板: Python
標題: [翻譯] Google 建議的 Python 風格指南 28,29
時間: Tue May 14 20:05:25 2013
原文網址: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.
"""