<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                ### 導航 - [索引](../genindex.xhtml "總目錄") - [模塊](../py-modindex.xhtml "Python 模塊索引") | - [下一頁](datastructures.xhtml "5. 數據結構") | - [上一頁](introduction.xhtml "3. Python 的非正式介紹") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) ? - zh\_CN 3.7.3 [文檔](../index.xhtml) ? - [Python 教程](index.xhtml) ? - $('.inline-search').show(0); | # 4. 其他流程控制工具 除了剛剛介紹過的 [`while`](../reference/compound_stmts.xhtml#while) 語句,Python中也有其他語言常用的流程控制語句,只是稍有不同。 ## 4.1. `if` 語句 可能最為人所熟知的編程語句就是 [`if`](../reference/compound_stmts.xhtml#if) 語句了。例如: ``` >>> x = int(input("Please enter an integer: ")) Please enter an integer: 42 >>> if x < 0: ... x = 0 ... print('Negative changed to zero') ... elif x == 0: ... print('Zero') ... elif x == 1: ... print('Single') ... else: ... print('More') ... More ``` 可以有零個或多個 [`elif`](../reference/compound_stmts.xhtml#elif) 部分,以及一個可選的 [`else`](../reference/compound_stmts.xhtml#else) 部分。 關鍵字 '`elif`' 是 'else if' 的縮寫,適合用于避免過多的縮進。 一個 `if` ... `elif` ... `elif` ... 序列可以看作是其他語言中的 `switch` 或 `case` 語句的替代。 ## 4.2. `for` 語句 Python 中的 [`for`](../reference/compound_stmts.xhtml#for) 語句與你在 C 或 Pascal 中可能用到的有所不同。 Python 中的 `for` 語句并不總是對算術遞增的數值進行迭代(如同 Pascal),或是給予用戶定義迭代步驟和暫停條件的能力(如同 C),而是對任意序列進行迭代(例如列表或字符串),條目的迭代順序與它們在序列中出現的順序一致。 例如(此處英文為雙關語): ``` >>> # Measure some strings: ... words = ['cat', 'window', 'defenestrate'] >>> for w in words: ... print(w, len(w)) ... cat 3 window 6 defenestrate 12 ``` 如果在循環內需要修改序列中的值(比如重復某些選中的元素),推薦你先拷貝一份副本。對序列進行循環不代表制作了一個副本進行操作。切片操作使這件事非常簡單: ``` >>> for w in words[:]: # Loop over a slice copy of the entire list. ... if len(w) > 6: ... words.insert(0, w) ... >>> words ['defenestrate', 'cat', 'window', 'defenestrate'] ``` 如果寫成 `for w in words:`,這個示例就會創建無限長的列表,一次又一次重復地插入 `defenestrate`。 ## 4.3. [`range()`](../library/stdtypes.xhtml#range "range") 函數 如果你確實需要遍歷一個數字序列,內置函數 [`range()`](../library/stdtypes.xhtml#range "range") 會派上用場。它生成算術級數: ``` >>> for i in range(5): ... print(i) ... 0 1 2 3 4 ``` 給定的終止數值并不在要生成的序列里;`range(10)` 會生成10個值,并且是以合法的索引生成一個長度為10的序列。range也可以以另一個數字開頭,或者以指定的幅度增加(甚至是負數;有時這也被叫做 '步進') ``` range(5, 10) 5, 6, 7, 8, 9 range(0, 10, 3) 0, 3, 6, 9 range(-10, -100, -30) -10, -40, -70 ``` 要以序列的索引來迭代,您可以將 [`range()`](../library/stdtypes.xhtml#range "range") 和 [`len()`](../library/functions.xhtml#len "len") 組合如下: ``` >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>> for i in range(len(a)): ... print(i, a[i]) ... 0 Mary 1 had 2 a 3 little 4 lamb ``` 然而,在大多數這類情況下,使用 [`enumerate()`](../library/functions.xhtml#enumerate "enumerate") 函數比較方便,請參見 [循環的技巧](datastructures.xhtml#tut-loopidioms) 。 如果你只打印 range,會出現奇怪的結果: ``` >>> print(range(10)) range(0, 10) ``` [`range()`](../library/stdtypes.xhtml#range "range") 所返回的對象在許多方面表現得像一個列表,但實際上卻并不是。此對象會在你迭代它時基于所希望的序列返回連續的項,但它沒有真正生成列表,這樣就能節省空間。 我們說這樣的對象是 *可迭代的* ,也就是說,適合作為函數和結構體的參數,這些函數和結構體期望在迭代結束之前可以從中獲取連續的元素。我們已經看到 [`for`](../reference/compound_stmts.xhtml#for) 語句就是這樣一個迭代器。函數 [`list()`](../library/stdtypes.xhtml#list "list") 是另外一個;它從可迭代對象中創建列表。 ``` >>> list(range(5)) [0, 1, 2, 3, 4] ``` 后面,我們會看到更多返回可迭代對象的函數,和以可迭代對象作為參數的函數。 ## 4.4. `break` 和 `continue` 語句,以及循環中的 `else` 子句 [`break`](../reference/simple_stmts.xhtml#break) 語句,和 C 中的類似,用于跳出最近的 [`for`](../reference/compound_stmts.xhtml#for) 或 [`while`](../reference/compound_stmts.xhtml#while) 循環. 循環語句可能帶有一個 `else` 子句;它會在循環遍歷完列表 (使用 [`for`](../reference/compound_stmts.xhtml#for)) 或是在條件變為假 (使用 [`while`](../reference/compound_stmts.xhtml#while)) 的時候被執行,但是不會在循環被 [`break`](../reference/simple_stmts.xhtml#break) 語句終止時被執行。 這可以通過以下搜索素數的循環為例來進行說明: ``` >>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print(n, 'equals', x, '*', n//x) ... break ... else: ... # loop fell through without finding a factor ... print(n, 'is a prime number') ... 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3 ``` (是的,這是正確的代碼。仔細看: `else` 子句屬于 [`for`](../reference/compound_stmts.xhtml#for) 循環, **不屬于** [`if`](../reference/compound_stmts.xhtml#if) 語句。) 當和循環一起使用時,`else` 子句與 [`try`](../reference/compound_stmts.xhtml#try) 語句中的 `else` 子句的共同點多于 [`if`](../reference/compound_stmts.xhtml#if) 語句中的子句: `try` 語句中的 `else` 子句會在未發生異常時執行,而循環中的 `else` 子句則會在未發生 `break` 時執行。 有關 `try` 語句和異常的更多信息,請參閱 [處理異常](errors.xhtml#tut-handling)。 [`continue`](../reference/simple_stmts.xhtml#continue) 語句也是借鑒自 C 語言,表示繼續循環中的下一次迭代: ``` >>> for num in range(2, 10): ... if num % 2 == 0: ... print("Found an even number", num) ... continue ... print("Found a number", num) Found an even number 2 Found a number 3 Found an even number 4 Found a number 5 Found an even number 6 Found a number 7 Found an even number 8 Found a number 9 ``` ## 4.5. `pass` 語句 [`pass`](../reference/simple_stmts.xhtml#pass) 語句什么也不做。當語法上需要一個語句,但程序需要什么動作也不做時,可以使用它。例如: ``` >>> while True: ... pass # Busy-wait for keyboard interrupt (Ctrl+C) ... ``` 這通常用于創建最小的類: ``` >>> class MyEmptyClass: ... pass ... ``` [`pass`](../reference/simple_stmts.xhtml#pass) 的另一個可以使用的場合是在你編寫新的代碼時作為一個函數或條件子句體的占位符,允許你保持在更抽象的層次上進行思考。 `pass` 會被靜默地忽略: ``` >>> def initlog(*args): ... pass # Remember to implement this! ... ``` ## 4.6. 定義函數 我們可以創建一個輸出任意范圍內 Fibonacci 數列的函數: ``` >>> def fib(n): # write Fibonacci series up to n ... """Print a Fibonacci series up to n.""" ... a, b = 0, 1 ... while a < n: ... print(a, end=' ') ... a, b = b, a+b ... print() ... >>> # Now call the function we just defined: ... fib(2000) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 ``` 關鍵字 [`def`](../reference/compound_stmts.xhtml#def) 引入一個函數 *定義*。它必須后跟函數名稱和帶括號的形式參數列表。構成函數體的語句從下一行開始,并且必須縮進。 函數體的第一個語句可以(可選的)是字符串文字;這個字符串文字是函數的文檔字符串或 *docstring* 。(有關文檔字符串的更多信息,請參閱 [文檔字符串](#tut-docstrings) 部分)有些工具使用文檔字符串自動生成在線或印刷文檔,或者讓用戶以交互式的形式瀏覽代碼;在你編寫的代碼中包含文檔字符串是一種很好的做法,所以要養成習慣。 函數的 *執行* 會引入一個用于函數局部變量的新符號表。更確切地說,函數中的所有變量賦值都將值存儲在本地符號表中;而變量引用首先在本地符號表中查找,然后在封閉函數的本地符號表中查找,然后在全局符號表中查找,最后在內置符號表中查找。所以全局變量不能直接在函數中賦值(除非使用 [`global`](../reference/simple_stmts.xhtml#global) 命名),盡管可以引用它們。 在函數被調用時,實際參數(實參)會被引入被調用函數的本地符號表中;因此,實參是通過 *按值調用* 傳遞的(其中 *值* 始終是對象 *引用* 而不是對象的值)。[1](#id2) 當一個函數調用另外一個函數時,將會為該調用創建一個新的本地符號表。 函數定義會把函數名引入當前的符號表中。函數名稱的值具有解釋器將其識別為用戶定義函數的類型。這個值可以分配給另一個名稱,該名稱也可以作為一個函數使用。這用作一般的重命名機制: ``` >>> fib <function fib at 10042ed0> >>> f = fib >>> f(100) 0 1 1 2 3 5 8 13 21 34 55 89 ``` 如果你學過其他語言,你可能會認為 `fib` 不是函數而是一個過程,因為它并不返回值。事實上,即使沒有 [`return`](../reference/simple_stmts.xhtml#return) 語句的函數也會返回一個值,盡管它是一個相當無聊的值。這個值稱為 `None` (它是內置名稱)。一般來說解釋器不會打印出單獨的返回值 `None` ,如果你真想看到它,你可以使用 [`print()`](../library/functions.xhtml#print "print") ``` >>> fib(0) >>> print(fib(0)) None ``` 寫一個返回斐波那契數列的列表,而不是打印出來的函數,非常簡單: ``` >>> def fib2(n): # return Fibonacci series up to n ... """Return a list containing the Fibonacci series up to n.""" ... result = [] ... a, b = 0, 1 ... while a < n: ... result.append(a) # see below ... a, b = b, a+b ... return result ... >>> f100 = fib2(100) # call it >>> f100 # write the result [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] ``` 此示例中,像往常一樣,演示了一些新的 Python 功能: - [`return`](../reference/simple_stmts.xhtml#return) 語句會從函數內部返回一個值。 不帶表達式參數的 `return` 會返回 `None`。 函數執行完畢退出也會返回 `None`。 - `result.append(a)` 語句調用了列表對象 `result` 的\* 。方法是 '屬于' 一個對象的函數,它被命名為 `obj.methodname` ,其中 `obj` 是某個對象(也可能是一個表達式), `methodname` 是由對象類型中定義的方法的名稱。不同的類型可以定義不同的方法。不同類型的方法可以有相同的名稱而不會引起歧義。(可以使用 *類* 定義自己的對象類型和方法,請參閱 [類](classes.xhtml#tut-classes) )示例中的方法 `append()` 是為列表對象定義的;它會在列表的最后添加一個新的元素。在這個示例中它相當于 `result = result + [a]` ,但更高效。 ## 4.7. 函數定義的更多形式 給函數定義有可變數目的參數也是可行的。這里有三種形式,可以組合使用。 ### 4.7.1. 參數默認值 最有用的形式是對一個或多個參數指定一個默認值。這樣創建的函數,可以用比定義時允許的更少的參數調用,比如: ``` def ask_ok(prompt, retries=4, reminder='Please try again!'): while True: ok = input(prompt) if ok in ('y', 'ye', 'yes'): return True if ok in ('n', 'no', 'nop', 'nope'): return False retries = retries - 1 if retries < 0: raise ValueError('invalid user response') print(reminder) ``` 這個函數可以通過幾種方式調用: - 只給出必需的參數:`ask_ok('Do you really want to quit?')` - 給出一個可選的參數:`ask_ok('OK to overwrite the file?', 2)` - 或者給出所有的參數:`ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')` 這個示例還介紹了 [`in`](../reference/expressions.xhtml#in) 關鍵字。它可以測試一個序列是否包含某個值。 默認值是在 *定義過程* 中在函數定義處計算的,所以 ``` i = 5 def f(arg=i): print(arg) i = 6 f() ``` 會打印 `5`。 **重要警告:** 默認值只會執行一次。這條規則在默認值為可變對象(列表、字典以及大多數類實例)時很重要。比如,下面的函數會存儲在后續調用中傳遞給它的參數: ``` def f(a, L=[]): L.append(a) return L print(f(1)) print(f(2)) print(f(3)) ``` 這將打印出 ``` [1] [1, 2] [1, 2, 3] ``` 如果你不想要在后續調用之間共享默認值,你可以這樣寫這個函數: ``` def f(a, L=None): if L is None: L = [] L.append(a) return L ``` ### 4.7.2. 關鍵字參數 也可以使用形如 `kwarg=value` 的 [關鍵字參數](../glossary.xhtml#term-keyword-argument) 來調用函數。例如下面的函數: ``` def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): print("-- This parrot wouldn't", action, end=' ') print("if you put", voltage, "volts through it.") print("-- Lovely plumage, the", type) print("-- It's", state, "!") ``` 接受一個必需的參數(`voltage`)和三個可選的參數(`state`, `action`,和 `type`)。這個函數可以通過下面的任何一種方式調用: ``` parrot(1000) # 1 positional argument parrot(voltage=1000) # 1 keyword argument parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments parrot('a million', 'bereft of life', 'jump') # 3 positional arguments parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword ``` 但下面的函數調用都是無效的: ``` parrot() # required argument missing parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument parrot(110, voltage=220) # duplicate value for the same argument parrot(actor='John Cleese') # unknown keyword argument ``` 在函數調用中,關鍵字參數必須跟隨在位置參數的后面。傳遞的所有關鍵字參數必須與函數接受的其中一個參數匹配(比如 `actor` 不是函數 `parrot` 的有效參數),它們的順序并不重要。這也包括非可選參數,(比如 `parrot(voltage=1000)` 也是有效的)。不能對同一個參數多次賦值。下面是一個因為此限制而失敗的例子: ``` >>> def function(a): ... pass ... >>> function(0, a=0) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: function() got multiple values for keyword argument 'a' ``` 當在最后出現形如 `**name` 的形式參數時,它會接受一個字典(參見 [映射類型 --- dict](../library/stdtypes.xhtml#typesmapping) )字典中包含了所有除了與形式參數對應的其他關鍵字參數。這可以和形如 `*name` 的形式參數(在下一小節描述)結合,該參數會接受一個包含形式參數列表之外的位置參數的元組。(`*name` 必須在出現在 `**name` 之前。)比如,如果我們定義一個這樣的函數: ``` def cheeseshop(kind, *arguments, **keywords): print("-- Do you have any", kind, "?") print("-- I'm sorry, we're all out of", kind) for arg in arguments: print(arg) print("-" * 40) for kw in keywords: print(kw, ":", keywords[kw]) ``` 它可以像這樣調用: ``` cheeseshop("Limburger", "It's very runny, sir.", "It's really very, VERY runny, sir.", shopkeeper="Michael Palin", client="John Cleese", sketch="Cheese Shop Sketch") ``` 當然它會打印: ``` -- Do you have any Limburger ? -- I'm sorry, we're all out of Limburger It's very runny, sir. It's really very, VERY runny, sir. ---------------------------------------- shopkeeper : Michael Palin client : John Cleese sketch : Cheese Shop Sketch ``` 注意打印時關鍵字參數的順序保證與調用函數時提供它們的順序是相匹配的。 ### 4.7.3. 任意的參數列表 最后,最不常用的選項是可以使用任意數量的參數調用函數。這些參數會被包含在一個元組里(參見 [元組和序列](datastructures.xhtml#tut-tuples) )。在可變數量的參數之前,可能會出現零個或多個普通參數。: ``` def write_multiple_items(file, separator, *args): file.write(separator.join(args)) ``` 一般來說,這些 `可變參數` 將在形式參數列表的末尾,因為它們收集傳遞給函數的所有剩余輸入參數。出現在 `*args` 參數之后的任何形式參數都是 ‘僅關鍵字參數’,也就是說它們只能作為關鍵字參數而不能是位置參數。: ``` >>> def concat(*args, sep="/"): ... return sep.join(args) ... >>> concat("earth", "mars", "venus") 'earth/mars/venus' >>> concat("earth", "mars", "venus", sep=".") 'earth.mars.venus' ``` ### 4.7.4. 解包參數列表 當參數已經在列表或元組中但需要為需要單獨位置參數的函數調用解包時,會發生相反的情況。例如,內置的 [`range()`](../library/stdtypes.xhtml#range "range") 函數需要單獨的 *start* 和 *stop* 參數。如果它們不能單獨使用,請使用 `*` 運算符編寫函數調用以從列表或元組中解包參數: ``` >>> list(range(3, 6)) # normal call with separate arguments [3, 4, 5] >>> args = [3, 6] >>> list(range(*args)) # call with arguments unpacked from a list [3, 4, 5] ``` 以同樣的方式,字典可以使用 `**` 運算符來提供關鍵字參數: ``` >>> def parrot(voltage, state='a stiff', action='voom'): ... print("-- This parrot wouldn't", action, end=' ') ... print("if you put", voltage, "volts through it.", end=' ') ... print("E's", state, "!") ... >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"} >>> parrot(**d) -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised ! ``` ### 4.7.5. Lambda 表達式 可以用 [`lambda`](../reference/expressions.xhtml#lambda) 關鍵字來創建一個小的匿名函數。這個函數返回兩個參數的和: `lambda a, b: a+b` 。Lambda函數可以在需要函數對象的任何地方使用。它們在語法上限于單個表達式。從語義上來說,它們只是正常函數定義的語法糖。與嵌套函數定義一樣,lambda函數可以引用包含范圍的變量: ``` >>> def make_incrementor(n): ... return lambda x: x + n ... >>> f = make_incrementor(42) >>> f(0) 42 >>> f(1) 43 ``` 上面的例子使用一個lambda表達式來返回一個函數。另一個用法是傳遞一個小函數作為參數: ``` >>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] >>> pairs.sort(key=lambda pair: pair[1]) >>> pairs [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')] ``` ### 4.7.6. 文檔字符串 以下是有關文檔字符串的內容和格式的一些約定。 第一行應該是對象目的的簡要概述。為簡潔起見,它不應顯式聲明對象的名稱或類型,因為這些可通過其他方式獲得(除非名稱恰好是描述函數操作的動詞)。這一行應以大寫字母開頭,以句點結尾。 如果文檔字符串中有更多行,則第二行應為空白,從而在視覺上將摘要與其余描述分開。后面幾行應該是一個或多個段落,描述對象的調用約定,它的副作用等。 Python解析器不會從Python中刪除多行字符串文字的縮進,因此處理文檔的工具必須在需要時刪除縮進。這是使用以下約定完成的。文檔字符串第一行 *之后* 的第一個非空行確定整個文檔字符串的縮進量。(我們不能使用第一行,因為它通常與字符串的開頭引號相鄰,因此它的縮進在字符串文字中不明顯。)然后從字符串的所有行的開頭剝離與該縮進 "等效" 的空格。 縮進的行不應該出現,但是如果它們出現,則應該剝離它們的所有前導空格。應在擴展標簽后測試空白的等效性(通常為8個空格)。 下面是一個多行文檔字符串的例子: ``` >>> def my_function(): ... """Do nothing, but document it. ... ... No, really, it doesn't do anything. ... """ ... pass ... >>> print(my_function.__doc__) Do nothing, but document it. No, really, it doesn't do anything. ``` ### 4.7.7. 函數標注 [函數標注](../reference/compound_stmts.xhtml#function) 是關于用戶自定義函數中使用的類型的完全可選元數據信息(有關詳情請參閱 [**PEP 3107**](https://www.python.org/dev/peps/pep-3107) \[https://www.python.org/dev/peps/pep-3107\] 和 [**PEP 484**](https://www.python.org/dev/peps/pep-0484) \[https://www.python.org/dev/peps/pep-0484\] )。 [函數標注](../glossary.xhtml#term-function-annotation) 以字典的形式存放在函數的 `__annotations__` 屬性中,并且不會影響函數的任何其他部分。 形參標注的定義方式是在形參名稱后加上冒號,后面跟一個表達式,該表達式會被求值為標注的值。 返回值標注的定義方式是加上一個組合符號 `->`,后面跟一個表達式,該標注位于形參列表和表示 [`def`](../reference/compound_stmts.xhtml#def) 語句結束的冒號之間。 下面的示例有一個位置參數,一個關鍵字參數以及返回值帶有相應標注: ``` >>> def f(ham: str, eggs: str = 'eggs') -> str: ... print("Annotations:", f.__annotations__) ... print("Arguments:", ham, eggs) ... return ham + ' and ' + eggs ... >>> f('spam') Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>} Arguments: spam eggs 'spam and eggs' ``` ## 4.8. 小插曲:編碼風格 現在你將要寫更長,更復雜的Python代碼,是時候討論一下 *代碼風格*。大多數語言都能使用不同的風格編寫(或更簡潔,格式化的);有些比其他的更具有可讀性。能讓其他人輕松閱讀你的代碼總是一個好主意,采用一種好的編碼風格對此有很大幫助。 對于Python,[**PEP 8**](https://www.python.org/dev/peps/pep-0008) \[https://www.python.org/dev/peps/pep-0008\] 已經成為大多數項目所遵循的風格指南;它促進了一種非常易讀且令人賞心悅目的編碼風格。每個Python開發人員都應該在某個時候閱讀它;以下是為你提取的最重要的幾個要點: - 使用4個空格縮進,不要使用制表符。 4個空格是一個在小縮進(允許更大的嵌套深度)和大縮進(更容易閱讀)的一種很好的折中方案。制表符會引入混亂,最好不要使用它。 - 換行,使一行不超過79個字符。 這有助于使用小型顯示器的用戶,并且可以在較大的顯示器上并排放置多個代碼文件。 - 使用空行分隔函數和類,以及函數內的較大的代碼塊。 - 如果可能,把注釋放到單獨的一行。 - 使用文檔字符串。 - 在運算符前后和逗號后使用空格,但不能直接在括號內使用: `a = f(1, 2) + g(3, 4)`。 - 類和函數命名的一致性;規范是使用 `CamelCase` 命名類,`lower_case_with_underscores` 命名函數和方法。始終使用 `self` 作為第一個方法參數的名稱(有關類和方法,請參閱 [初探類](classes.xhtml#tut-firstclasses) )。 - 如果你的代碼旨在用于國際環境,請不要使用花哨的編碼。Python 默認的 UTF-8 或者純 ASCII 在任何情況下都能有最好的表現。 - 同樣,哪怕只有很小的可能,遇到說不同語言的人閱讀或維護代碼,也不要在標識符中使用非ASCII字符。 腳注 [1](#id1)實際上,*通過對象引用調用* 會是一個更好的表述,因為如果傳遞的是可變對象,則調用者將看到被調用者對其做出的任何更改(插入到列表中的元素)。 ### 導航 - [索引](../genindex.xhtml "總目錄") - [模塊](../py-modindex.xhtml "Python 模塊索引") | - [下一頁](datastructures.xhtml "5. 數據結構") | - [上一頁](introduction.xhtml "3. Python 的非正式介紹") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) ? - zh\_CN 3.7.3 [文檔](../index.xhtml) ? - [Python 教程](index.xhtml) ? - $('.inline-search').show(0); | ? [版權所有](../copyright.xhtml) 2001-2019, Python Software Foundation. Python 軟件基金會是一個非盈利組織。 [請捐助。](https://www.python.org/psf/donations/) 最后更新于 5月 21, 2019. [發現了問題](../bugs.xhtml)? 使用[Sphinx](http://sphinx.pocoo.org/)1.8.4 創建。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看