這章的主題是“抽象”。主要內容大概包括如何將語句組織成函數。有了函數以后就不必反反復復向計算機傳遞同樣的指令了。還會介紹參數、作用域,遞歸的概念及其在程序中的用途。
使用下面的代碼:
def hello(name): return 'Hello, ' + name + '!'>>> PRint hello('world')Hello, world!>>> print hello('Gumby')Hello, Gumby!如果在函數的開頭寫下字符串,他就會作為函數的一部分進行存儲,這稱為文檔字符串。
使用下面的代碼:
>>> def square(x):... 'Calculates the square of the number x.'... return x*x...>>> square.__doc__'Calculates the square of the number x.'內建的help函數是非常有用的。使用下面的代碼:
>>> help(square)Help on function square in module __main__:square(x) Calculates the square of the number x.所有的函數都返回了東西,當不需要它們返回值的時候,它們就返回None
有時候,參數的順序是很難記住的,為了讓事情簡單些,可以提供參數的名字。
使用下面的代碼:
>>> def hello_1(greeting,name):... print ('%s, %s!'%(greeting,name))...>>> hello_1(greeting="Hello",name="world")Hello, world!這類使用參數名提供的參數叫做關鍵字參數。每個參賽的含義變得更加清晰,而且就算弄亂了參數的順序,對于程序的功能也沒有任何影響。
而且關鍵字參數在函數中給參數提供默認值。
有些時候讓用戶提供任意數量的參數是很有用的。這其實不難。
使用下面的代碼:
>>> def print_params(*params):... print params...>>> print_params('Testing')('Testing',)>>>>>> print_params('Testing','param2')('Testing', 'param2')>>>>>> print_params(1,2,3)(1, 2, 3)將關鍵詞參數和收集參數結合起來,這一部分覺得沒什么用,先跳過了。
這一部分也跳過了。
只說一點,如果在一個函數內部要使用全局變量,需要用到global進行聲明。使用下面的代碼:
>>> x = 1>>> def change_global():... global x... x = x+1...>>> change_global()>>> x2這部分也跳過了
新聞熱點
疑難解答