Python 學習之旅,先來看看 Python 的代碼規範,讓本身先有個意識,並且在日後的學習中慢慢養成習慣html
#-*-coding:utf-8-*-
標識每行代碼儘可能不超過 80 個字符(在特殊狀況下能夠略微超過 80 ,但最長不得超過 120)python
理由:正則表達式
簡單說,天然語言使用雙引號,機器標示使用單引號,所以 代碼裏 多數應該使用 單引號session
"..."
u"你好世界"
'...'
r"..."
"""......"""
class A: def __init__(self): pass def hello(self): pass def main(): pass
#-*-conding:utf-8-*-
標識# 正確的寫法 import os import sys # 不推薦的寫法 import sys,os # 正確的寫法 from subprocess import Popen, PIPE
# 正確的寫法 from foo.bar import Bar # 不推薦的寫法 from ..bar import Bar
import os import sys import msgpack import zmq import foo
from myclass import MyClass
import bar import foo.bar bar.Bar() foo.bar.Bar()
[=,-,+=,==,>,in,is not, and]
:# 正確的寫法 i = i + 1 submitted += 1 x = x * 2 - 1 hypot2 = x * x + y * y c = (a + b) * (a - b) # 不推薦的寫法 i=i+1 submitted +=1 x = x*2 - 1 hypot2 = x*x + y*y c = (a+b) * (a-b)
,
以後要有空格# 正確的寫法 def complex(real, imag): pass # 不推薦的寫法 def complex(real,imag): pass
# 正確的寫法 def complex(real, imag=0.0): pass # 不推薦的寫法 def complex(real, imag = 0.0): pass
# 正確的寫法 spam(ham[1], {eggs: 2}) # 不推薦的寫法 spam( ham[1], { eggs : 2 } )
# 正確的寫法 dict['key'] = list[index] # 不推薦的寫法 dict ['key'] = list [index]
# 正確的寫法 x = 1 y = 2 long_variable = 3 # 不推薦的寫法 x = 1 y = 2 long_variable = 3
Python 支持括號內的換行。這時有兩種狀況。app
1) 第二行縮進到括號的起始處編輯器
foo = long_function_name(var_one, var_two, var_three, var_four)
2) 第二行縮進 4 個空格,適用於起始括號就換行的情形ide
def long_function_name( var_one, var_two, var_three, var_four): print(var_one)
使用反斜槓\
換行,二元運算符+
.
等應出如今行末;長字符串也能夠用此法換行函數
session.query(MyTable).\ filter_by(id=1).\ one() print 'Hello, '\ '%s %s!' %\ ('Harry', 'Potter')
禁止複合語句,即一行中包含多個語句:工具
# 正確的寫法 do_first() do_second() do_third() # 不推薦的寫法 do_first();do_second();do_third();
if/for/while
必定要換行:post
# 正確的寫法 if foo == 'blah': do_blah_thing() # 不推薦的寫法 if foo == 'blah': do_blash_thing()
docstring 的規範中最其本的兩點:
"""Return a foobar Optional plotz says to frobnicate the bizbaz first. """ """Oneline docstring"""
「#」號後空一格,段落件用空行分開(一樣須要「#」號)
# 塊註釋 # 塊註釋 # # 塊註釋 # 塊註釋
至少使用兩個空格和語句分開,注意不要使用無心義的註釋
# 正確的寫法 x = x + 1 # 邊框加粗一個像素 # 不推薦的寫法(無心義的註釋) x = x + 1 # x加1
在代碼的關鍵部分(或比較複雜的地方), 能寫註釋的要儘可能寫註釋
app = create_app(name, options) # ===================================== # 請勿在此處添加 get post等app路由行爲 !!! # ===================================== if __name__ == '__main__': app.run()
做爲文檔的Docstring通常出如今模塊頭部、函數和類的頭部,這樣在python中能夠經過對象的__doc__對象獲取文檔.
編輯器和IDE也能夠根據Docstring給出自動提示.
# -*- coding: utf-8 -*- """Example docstrings. This module demonstrates documentation as specified by the `Google Python Style Guide`_. Docstrings may extend over multiple lines. Sections are created with a section header and a colon followed by a block of indented text. Example: Examples can be given using either the ``Example`` or ``Examples`` sections. Sections support any reStructuredText formatting, including literal blocks:: $ python example_google.py Section breaks are created by resuming unindented text. Section breaks are also implicitly created anytime a new section starts. """
# 不推薦的寫法(不要寫函數原型等廢話) def function(a, b): """function(a, b) -> list""" ... ... # 正確的寫法 def function(a, b): """計算並返回a到b範圍內數據的平均值""" ... ...
def func(arg1, arg2): """在這裏寫函數的一句話總結(如: 計算平均值). 這裏是具體描述. 參數 ---------- arg1 : int arg1的具體描述 arg2 : int arg2的具體描述 返回值 ------- int 返回值的具體描述 參看 -------- otherfunc : 其它關聯函數等... 示例 -------- 示例使用doctest格式, 在`>>>`後的代碼能夠被文檔測試工具做爲測試用例自動運行 >>> a=[1,2,3] >>> print [x + 3 for x in a] [4, 5, 6] """
文檔註釋不限於中英文, 但不要中英文混用
文檔註釋不是越長越好, 一般一兩句話能把狀況說清楚便可
# 正確的模塊名 import decoder import html_parser # 不推薦的模塊名 import Decoder
class Farm(): pass class AnimalFarm(Farm): pass class _PrivateFarm(Farm): pass
def run(): pass def run_with_env(): pass
class Person(): def _private_func(): pass
if __name__ == '__main__': count = 0 school_name = ''
MAX_CLIENT = 100 MAX_CONNECTION = 1000 CONNECTION_TIMEOUT = 600
MAX_OVERFLOW = 100 Class FooBar: def foo_bar(self, print_): print(print_)