函數(shù) 函數(shù)通過 def max(a,b): if a>b: print a else: print b max(3,5) 5 使用global語句,可以將一個(gè)變量聲明為全局變量,即使在函數(shù)內(nèi)部也可以為函數(shù)外部的變量賦值 x=10 def func(): global x x=20 print x func() 20 默認(rèn)參數(shù)值,當(dāng)用戶沒有給相應(yīng)參數(shù)提供值時(shí)將采用默認(rèn)的參數(shù)值,對于沒有默認(rèn)值的參數(shù)必須提供值 >>> def say(a,b=2): print a*b >>> say('hello') hellohello >>> say('hello',3) hellohellohello 關(guān)鍵參數(shù),用戶可以在使用時(shí)通過名稱來給自己想賦值的參數(shù)賦值 >>> def say(a,b=23,c=32): print 'a is',a,'b is',b,'c is',c >>> say(a=12,c=12) a is 12 b is 23 c is 12 return語句,默認(rèn)Python每個(gè)函數(shù)最后都暗含一個(gè)return None語句,表示該函數(shù)沒有任何返回值 >>> def say(): return 3 >>> say() 3 文檔字符串,類似于函數(shù),類等的說明 >>> def say(): '''這是一個(gè)函數(shù) 用于返回一個(gè)字符串''' print 'aaa' >>> help(say) Help on function say in module __main__: say() 這是一個(gè)函數(shù)
用于返回一個(gè)字符串 >>> print say.__doc__ 另一種查看文檔字符串的方法 注意雙下劃線 這是一個(gè)函數(shù) 用于返回一個(gè)字符串 模塊 如果你想要在其他程序中重用很多函數(shù),就需要使用模塊,模塊基本上就是一個(gè)包含了所有你定義的函數(shù)和變量的文件。為了在其他程序中重用模塊,模塊的文件名必須以.py為擴(kuò)展名。 模塊可以從其他程序 輸入 以便利用它的功能。這也是我們使用Python標(biāo)準(zhǔn)庫的方法。首先,我們將學(xué)習(xí)如何使用標(biāo)準(zhǔn)庫模塊。 >>> import sys 導(dǎo)入sys模塊 >>> print 'path is',sys.path 使用sys模塊中的path變量 path is ['C:\\Python23\\Lib\\idlelib', 'C:\\WINDOWS\\system32\\python23.zip', 'C:\\Python23', 'C:\\Python23\\DLLs', 'C:\\Python23\\lib', 'C:\\Python23\\lib\\plat-win', 'C:\\Python23\\lib\\lib-tk', 'C:\\Python23\\lib\\site-packages'] 當(dāng)一個(gè)模塊被第一次輸入的時(shí)候,這個(gè)模塊的主塊將被運(yùn)行。假如我們只想在程序本身被使用的時(shí)候運(yùn)行主塊,而在它被別的模塊輸入的時(shí)候不運(yùn)行主塊,我們該怎么做呢?這可以通過模塊的__name__屬性完成。每個(gè)Python模塊都有它的 if __name__ == '__main__': print 'This program is being run by itself' else: print 'I am being imported from another module' 創(chuàng)建你自己的模塊是十分簡單的,你一直在這樣做!每個(gè)Python程序也是一個(gè)模塊。你已經(jīng)確保它具有
上面是一個(gè) 模塊 的例子。你已經(jīng)看到,它與我們普通的Python程序相比并沒有什么特別之處。我們接下來將看看如何在我們別的Python程序中使用這個(gè)模塊。 記住這個(gè)模塊應(yīng)該被放置在我們輸入它的程序的同一個(gè)目錄中,或者在
mymodule.sayhi()
你可以使用內(nèi)建的 >>> def say(): return None >>> x=10 >>> dir() ['__builtins__', '__doc__', '__name__', 'say', 'x'] 當(dāng)你為 >>> import sys >>> dir(sys) ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'exc_clear', 'exc_info', 'exc_traceback', 'exc_type', 'exc_value', 'excepthook', 'exec_prefix', 'executable', 'exit', 'exitfunc', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', 'getwindowsversion', 'hexversion', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version', 'version_info', 'warnoptions', 'winver'] 注意,輸入的模塊同樣是列表的一部分。 >>> import sys >>> def say(): return None >>> x=10 >>> dir() ['__builtins__', '__doc__', '__name__', 'say', 'sys', 'x'] |
|