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