python開發(fā)深入編程0_第1頁
python開發(fā)深入編程0_第2頁
python開發(fā)深入編程0_第3頁
python開發(fā)深入編程0_第4頁
python開發(fā)深入編程0_第5頁
已閱讀5頁,還剩141頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

1、 Delphi/VCL 97 Perl Pascal MS-DOS Pascal 2006 NET/C# 2 Windows Linux NET 10 4 0 C# FX/BCLMSILSOS dll MVCLINQMetadata NET Python C ASM 2 Learning, 4th Edition ()Python Learning, 4th Edition()Python C 2 1. C2. 3. geventtornado er : qyuhenhotmsn: qyuhenhot com com com/qyuhen weibo: Q yuhen2012-01-113更新

2、記錄2012-02-092012-02-16第一章截稿,發(fā)布預(yù)覽版 0 1。第一章增加和修改了部分內(nèi)容。第二章截稿,發(fā)布預(yù)覽版 0 2。4目錄第一部分 Python 語言8第 1 章 基礎(chǔ)91.1 基本工具1 1 1 IPython991 1 2 Pdb / iPdb19常用函數(shù)環(huán)境初始化1 3 1 State2426291 3 2 Types311 3 3 builtin module331 3 4 sys module341 3 5 main module361 3 6 site module371 3 7 Run381 3 8 Finalize401.4 名字和名字空間42名字空間名字訪

3、問方式4 2 對(duì)性能的影響481.5 類型和對(duì)象51對(duì)象的內(nèi)存布局類型對(duì)象.6 內(nèi)存管理1 6 1 內(nèi)存分配58595弱引用垃圾回收.7 編譯和反編譯79編譯反編譯7 3 動(dòng)態(tài)執(zhí)行881 7 4 代碼混淆911.8 小結(jié)第 2 章 內(nèi)置類型93942.1 數(shù)字2 1 1 bool94942 1 2 int952 1 3 long1012 1 4 float1022.2 字符串2 2 1 str1041042 2 2 unicode1112.3 列表2 3 1 list1191192 3 2 tuple1252 3 3 array1292.4 字典2 4 1 dict1321332 4 2 de

4、faultdict1442 4 3 OrderedDict145集合小結(jié)1451476第 3 章 表達(dá)式第章 函數(shù)第章 迭代器第 6 章 模塊第章 類第章 異常第 9 章 Descriptor154第 10 章 Decorator155第 11 章 Metaclass156第二部分 Python 標(biāo)準(zhǔn)庫(kù)157158第三部分 第三方庫(kù)7Python 語言要誤會(huì),我不會(huì)象大多數(shù)書那樣去慢條斯理地逐個(gè)介紹語法。我們要面對(duì)的是一次探險(xiǎn)旅程。驚收拾工具,整理好行囊,你將是探險(xiǎn)團(tuán)隊(duì)中的重要一員心動(dòng)魄 的狀況。你可能要一頭扎入源碼里尋幽探秘,也或者是在調(diào)試器里面對(duì)一堆十六進(jìn)制數(shù)字發(fā)呆。之,不要指望這本書會(huì)按

5、常規(guī)出牌,我希望能有驚悚就丟在一旁,白白浪費(fèi)了金錢和時(shí)間,還可能成為家里的衛(wèi)生死角。人建議,在看本書的同時(shí),把你喜歡的經(jīng)典書籍放在旁邊 (我喜歡紙質(zhì)書,看電子書無法專心) 互為參考。好吧,讓我們開始探索Q.yuhen:實(shí)說,寫這些廢話比寫代碼困難多了8 1 TourLinux OS X Windows OS X Lion 10 7 32.7 C/wwwI0.12 IPdb easy_install pdb GDB GCC ( 27 2) CJython Iron1.1 1.1.1 IIPython FunctionI IDE I *nix S PyCharm IDE *nix IDE VIM

6、IDE n NET Visual Studio NET Console Wri IDE ine 9要多,我們先掌握幾個(gè)基本的 IPyhton要習(xí)慣 help、man 等命令。Function 用法就行。作為在終端下生存的一員,隨時(shí)可以用 鍵做代碼自動(dòng)完成,多數(shù)時(shí)候可以省略Function 的 % 前綴符號(hào)。10$ i2.7.1 (r271:86832, Jun 16 2011, 16:59:05)Type copyright, credits or license for more information.I0.12 - An enhancederactive.?-roduction and

7、overview of Is features.%quickref - Quick reference.help-s own help system.object?- Details about object, use object? for extra details.In 1:命令說明%quickrefI使用快速導(dǎo)引?, ?象、MagicFunction 等信息!執(zhí)行 Sd%sc, %sx捕獲 Sd 輸出結(jié)果%pwd查看當(dāng)前工作目錄%cd工作目錄跳轉(zhuǎn)%pushd, %popd, %dirs目錄棧操作%bookmark目錄書簽%save保存操作歷史%logstart,%logstoplog

8、記錄器%edit編輯源碼文件%pycat, %pfile顯示源碼%who, %whos查看當(dāng)前環(huán)境下的所有對(duì)象%run執(zhí)行源碼文件%prun, %time, %timeit性能測(cè)試%pdb開打或關(guān)閉調(diào)試器%reset重置執(zhí)行環(huán)境,刪除全部變量%quit退出 I 幫助%quickref 顯示 Quick Reference Card,建議仔細(xì)閱讀,并盡可能把所有的功能都實(shí)驗(yàn)一遍。? 顯示目標(biāo)的基本信息,而 ? 返回的信息更加詳細(xì),比如查看函數(shù)、模塊的源碼。當(dāng)你閱讀某個(gè)開源項(xiàng)目(比如 tornado)源碼時(shí),使用 pdb 顯示 Call Stack Frames 獲得執(zhí)行流程,然后配合 ? 查看相

9、關(guān)對(duì)象和函數(shù)的源碼。豈不比用一個(gè)文本編輯器亂哄哄地查找好?Python 作為一種動(dòng)態(tài)語言,很多東西是在運(yùn)行時(shí)生成和改變的,不能用 Ctags 的老習(xí)慣來對(duì)待。11In 2: def test():# 定義一個(gè)包含了 doc 的函數(shù).:.:haha, test.:.:pass.:In 3: test?# 查看函數(shù)信息,包括 doc 。Type:functionBase Class: String Form: Namespace: InteractiveDefinition: test()Docstring: haha, test.In 4: test?# 更多信息?比如源碼!Type:funct

10、ionBase Class: String Form: Namespace: InteractiveDefinition: test()Source:def test(): haha, test.passIPython - An enhanced Interactive Python - Quick Reference Card=obj?, obj?: Get help, or more help for object (also works as?obj, ?obj).?foo.*abc*: List names in foo containing abc in them.%magic: I

11、nformation about IPythons magic % functions.Magic functions are prefixed by %, and typically take their arguments without parentheses, quotes or even commas for convenience. . Maigc Function pydoc ! () S Sd $var_name d $env_var12In 8: !ls /etcafpovertcp.cfghosts.equivpf.anchorsaliasesirbrcpf.confIn

12、6: import sysIn 7: sys._getframe ?Type:builtin_function_or_methodBase Class: String Form: Namespace:eractiveDocstring:_getframe(depth) - frameobjectReturn a frame object from the call stack. If optionaleger depth is given, return the frame objectt many calls below the top of the stack. Ift is deeper

13、n the call stack, ValueError is raised. The default for depth is zero, returning the frame at the top of the call stack.This function should be used forernal and spelized pures only.In 5: %bookmark?Type:functionBase Class: Namespace: IernalDefinition: %bookmark(self, parameter_s=)Docstring:Manage Is

14、 bookmark system.%bookmark - set bookmark to current dir%bookmark - set bookmark to %bookmark -l- list all bookmarks%bookmark -d - remove bookmark%bookmark -r- remove all bookmarks. . %sc%sx Sd %sc: %sx: list I S%pwd: %cd: %pushd, %popd, %dirs: 13In 16: pwdOut16: u/Users/test/In 17: cd /bin/binIn 12

15、: %sc s = ls In 13: sOut13: DesktopnsnDownloadsnLibrarynMoviesnMusicnPicturesnPublicn In 14: l = %sx ls In 15: lOut15:Desktop,s,Downloads, Library, Movies,Music,Pictures, Public. .In 9: path = /binIn 10: !ls $path# : $var_name. .oddfhostnameln psshtest cpnamekilllspwdsleepunlinkIn 11: !echo $HOME# e

16、ll $ Python /Users/yuhen如果覺得目錄棧不方便,還可以用目錄書簽 (Bookmark)。%bookmark : 將當(dāng)前目錄加入書簽。%bookmark : 將指定目錄加入書簽。%bookmark -l: 顯示所有書簽。%bookmark -d : 刪除書簽。%bookmark -r: 刪除全部書簽。14In 22: bookmark learnPython# 將當(dāng)前目錄加入書簽,并取名為 learnPython In 23: bookmark ubin /usr/bin# 將某個(gè)目錄加入書簽In 24: bookmark -l# 看看所有的書簽Current bookma

17、rks:learnPython - /Users/test/python ubin- /usr/binIn 25: cd learnPython# 使用書簽跳轉(zhuǎn)(bookmark:learnPython) - /Users/test/python/Users/test/pythonIn 26: cd ubin# 再次使用書簽跳轉(zhuǎn)(bookmark:ubin) - /usr/bin/usr/binIn 27: pwd# 跳轉(zhuǎn)無誤!Out27: u/usr/binIn 28: cd -b learnPython# 如果擔(dān)心書簽名和某個(gè)子目錄名沖突,可以用 -b 參數(shù)。(bookmark:learn

18、Python) - /Users/test/python/Users/test/pythonIn 29: bookmark -d ubin# 刪除某個(gè)書簽In 30: bookmark -l Current bookmarks:learnPython - /Users/test/pythonIn 18: cd -# 回到上個(gè)目錄/Users/test/pythonIn 19: pushd /bin# 將當(dāng)前目錄壓入棧中,并跳轉(zhuǎn)到指定目錄/binOut19: u/Documents/Projects/learn/pythonIn 20: dirs# 查看目錄棧內(nèi)容,可以多次 pushd,按 FI

19、LO 彈出。Out20: u/Documents/Projects/learn/pythonIn 21: popd# 彈出目錄占中最后一個(gè)目錄,并跳轉(zhuǎn)。/Users/test/pythonpopd - /Documents/Projects/learn/python 記錄折騰了老半天,想不想把測(cè)試成果保存下來?%save 可以指定要保存的行號(hào)范圍。格式: %save options filename n1-n2 n3-n4參數(shù): -r 按照輸入的原始樣式保存。n5n6如果希望完整記錄實(shí)驗(yàn)過程,可以使用 log 功能。%logstart: 啟動(dòng)記錄器%logstop: 停止%logon, %lo

20、goff: 開啟或停止記錄%logstate: 查看記錄器狀態(tài)格式: %logstart -o|-r|-t log_name log_mode參數(shù): -o 保存 Out 內(nèi)容;-r 按輸入格式保存; -t 加入時(shí)間戳。模式: append 追加; backup 將已有的記錄文件改名; global 使用 $HOME 目錄下的單個(gè)記錄文件;over 覆蓋; rotate 創(chuàng)建 name 1 name 2 循環(huán)日志文件。15In 37: %logstart -r -t test.log over # 啟動(dòng)記錄器,over 表示 overwrite Activating auto-logging.

21、Current session state plus future input saved. Filename : test.logMode: overIn 31: a = 1In 32: b = a + 1In 33: p aFile , line 1 p aSyntaxError: invalid syntaxIn 34: print a 1In 35: save -r test.py 31-32 34# 將 31 32 行,還有第 34 行保存到 test.py。 The following commands were written to file test.py:a = 1b = a

22、 + 1 print aIn 36: cat test.py # coding: utf-8a = 1b = a + 1print a 編輯%edit 打開文本編輯器 (通常是 vi/vim),參數(shù)可以是源文件名,或某個(gè)對(duì)象名。-n: 指定源文件行號(hào);-x: 表示退出編輯器時(shí)不執(zhí)行該源碼。%ed 是縮寫別名。%pycat 高亮顯示源碼文件,%pfile 顯示某個(gè)對(duì)象所在的源碼文件。16In 47: ed -x main.pyOutput logging : False Raw input log : True Timestamping: True State: activeIn 38: a =

23、 1# 這些行會(huì)被記錄下來In 39: b = 2In 40: c = a + bIn 41: logoff# 暫時(shí)關(guān)閉記錄器,在 logon 之前的命令不會(huì)被記錄。Switching logging OFFIn 42: d = sum(a, b, c) # 被遺棄的賣姑娘的小火柴In 43: logon# 再次開始記錄Switching logging ON In 44: d = 100In 45: logstop# 停止記錄In 46: cat test.log# 看看記錄文件的內(nèi)容# IPython log file%logstart?%logstart -r -t test.log o

24、ver # Fri, 03 Feb 2012 11:46:09a = 1# Fri, 03 Feb 2012 11:46:10b = 2# Fri, 03 Feb 2012 11:46:14c = a + b# Fri, 03 Feb 2012 11:46:23logoff# Fri, 03 Feb 2012 11:46:54d = 100# Fri, 03 Feb 2012 11:47:01logstop %who %whos ed main py %run py -n: _name_ _main_ ( main)-i: -d: pdb-t: %time-p: profiler 17In 5

25、0: whomainpprsystestIn 51: whosVariableTypeData/Infomainfunctionpprmodulemodule ppr from /Sib/2.7/ppr.pyc sysmoduletestfunctionEditing.In 48: pycat main.py # -*- coding:utf-8 -*-import sys import pprdef test():pro, World!def main():test()if name = main : main()In 49: ed main.py# -x Editing. done. Ex

26、ecuting edited code.o, World! pdb%prun: %run -p profiler %time: %run -t %timeit: %time -n -r %pdb%reset18In 54: import timeIn 55: def test(n):for i in xrange(n):time.sleep(0.001):In 56: %prun test(10)13 function calls in 0.012 seconds Ordered by:ernal timencalls tottime percall cumtime percall filen

27、ame:lineno(function) 100.0120.0010.0120.001 time.sleep10.0000.0000.0120.012 :1(test)10.0000.0000.0120.012 :1()10.0000.0000.0000.000 method disable of _lsprof.Profiler objectsIn 57: %time test(10)CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s Wall time: 0.01 sIn 58: %timeit -n 100 -r 5 test(1)100

28、 loops, best of 5: 1.15 ms per loopIn 52: run main.py o, World!In 53: run -t main.py o, World!ICPU timings (estimated): User:0.00 s.System :0.00 s.Wall time:0.00 s.1.1.2 Pdb / iPdb pr gdb IDE IDE Debugger ipdb pdb Iipdb ipdbimport ipdb; ipdb.set_trace() ipdb I %pdb Automatic pdb calling”19In 1: cat

29、main.py #!/usr/bin/env# -*- coding:utf-8 -*-import sys import pprdef test(*args, *kwargs): prargsprkwargsraise Exception(Error!)def main():test(1, a, x = 10)if name = main : main()In 2: pdb# pdb Automatic pdb calling has been turned ONIn 3: run main.py# main.py test() (1, a)x: 10ExceptionTraceback (

30、most recent call last)/Users/test/main.py in () 15$-m ipdb main.py/Users/test/main.py(4)() 3 4 import sys5 import ppr運(yùn)行 %run -d 直接進(jìn)入調(diào)試狀態(tài)。常用的調(diào)試命令:20命令說明a, args顯示函數(shù)參數(shù)。b, break設(shè)置或顯示斷點(diǎn)列表。bt, w, where顯示 stack trace。c, cont, continue繼續(xù)執(zhí)行,直到下一個(gè)有效斷點(diǎn)。cl, clear清除斷點(diǎn)。d, down, u, up在 call stack frame 列表間移動(dòng)。disab

31、le, enable禁用或啟用斷點(diǎn)。In 3: run -d main.pyBreakpo1 at /Users/test/main.py:4NOTE: Enter c at the ipdb prompt to start your script.(1)()ipdb c# 注意上面的提示!/Users/test/main.py(4)() 31 4 import sys5 import ppripdb16 if name = main : 17main()/Users/test/main.pyain() 1112 def main(): 13test(1, a, x = 10) 14/User

32、s/test/main.pyest(*args, *kwargs)prargsprkwargs 10raise Exception(Error!) 1112 def main():Exception: Error!/Users/test/main.py(10)test()9prkwargs 10raise Exception(Error!) 11試試看:21In 4: run -d main.pyBreakpo1 at /Users/test/main.py:4NOTE: Enter c at the ipdb prompt to start your script.(1)()ipdb c#

33、注意上面的提示信息。/Users/test/main.py(4)() 31 4 import sys5 import ppripdb l# 查看源碼1 #!/usr/bin/env2 # -*- coding:utf-8 -*- 31 4 import sys5 import ppr 6def test(*args, *kwargs):prargsprkwargsraise Exception(Error!) 11ipdb l# 繼續(xù)查看后續(xù)源碼12 def main():命令說明exit, q, quit退出 pdb。h, help查看命令列表或詳細(xì)使用方法。ignore暫時(shí)忽略某個(gè)斷點(diǎn),可

34、設(shè)置忽略次數(shù)。l, list顯示源碼。n, next繼續(xù)執(zhí)行下一行代碼。p, pp顯示變量或表達(dá)式的結(jié)果。pp = pretty-pr。r, return繼續(xù)執(zhí)行,直到當(dāng)前函數(shù)結(jié)束。run, restart運(yùn)行,重新運(yùn)行。s, step續(xù)執(zhí)行下一行代碼,繼續(xù)函數(shù)內(nèi)部。tbreak創(chuàng)建臨時(shí)斷點(diǎn),命中后失效。whatis查看對(duì)象類型。1314151617test(1, a, x = 10)if name = main :main()ipdb b13# Breakpo2 at /Users/test/main.py:13ipdb btest# Breakpo3 at /Users/test/main

35、.py:7ipdb b# Num TypeDisp Enbkeep yesWhereat /Users/test/1breakpobre breakpobreakpo/main.py:4already hit 1 time2keep yeskeep yesat /Users/test/at /Users/test/main.py:13/main.py:73ipdb r# /main.py(13)main()/Users/test/12 def main():2- 13test(1, a, x = 10)14ipdb c# /main.py(8)test()/Users/test/37 def

36、test(*args, *kwargs): 8prprargskwargs9ipdb a# args = (1, a)kwargs = x: 10ipdb w# CallStack/System/Library/Frameworks/./2.7/bdb.py(383)run()381382cmd = cmd+ntry:exec cmd in globals, locals except BdbQuit:pass- 383384385(1)()/Users/test/main.py(17)()2131415test(1, a, x = 10)16 if name = main : 17main(

37、)/Users/test/11/main.py(13)main()22 I%pdb ipdb pm 23In 5: pdbAutomatic pdb calling has been turned OFFIn 6: run main.py (1, a)x: 10ExceptionTraceback (most recent call last)/Users/test/main.py in () 1516 if name = main : 17main()12 def main():2- 13test(1, a, x = 10)1415/Users/test/main.py(8)test() 6

38、37 def test(*args, *kwargs): 8prargsprkwargsraise Exception(Error!)ipdb u# StackFrame/Users/test/main.py(13)main()12 def main():2- 13test(1, a, x = 10)14ipdb d# StackFrame/Users/test/main.py(8)test()37 def test(*args, *kwargs): 8prargs9prkwargsipdb r# (1, a)x: 10-Return- e/Users/test/main.py(10)test

39、()9prkwargs 10raise Exception(Error!) 11ipdb q# pr I+ ipdb del reset1.2 id: Ctype: (Type)is: () dir: sys getsizeof: id gdb sys _get_frame: Call Stack (Stack Frame) sys _current_frames: 24In 1: hel)Help on built-in function idodule builtin :id(.)id(object) -eger/Users/test/main.pyain() 1112 def main(

40、): 13test(1, a, x = 10) 1415/Users/test/main.pyest(*args, *kwargs)prargsprkwargs 10raise Exception(Error!) 1112 def main():Exception: Error!In 7: ipdb.pm()# /Users/test/main.py(10)test()9prkwargs 10raise Exception(Error!) 11ipdb a# args = (1, a)kwargs = x: 10 gdb hex(id(a) gdb x 3xg 3 8 = _get_frame

41、 25In 12: import sysIn 7: class A(object):def eq (self, o):return True:In 8: a, b = A(), object() In 9: a = bOut9: TrueIn 10: a is b Out10: FalseIn 11: c = a; a is c Out11: True$ gdb -=ofGNU gdb 6.3.50-20050815 (Apple vergdb-1705) (Fri Jul 1 10:50:062011)(gdb) x/3xg 0 x7f83026a3950# 0 x7f83026a3950:

42、0 x00000000000000010 x0000000103b0a1800 x7f83026a3960:0 x0000000000001234Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (H: its the objects memory address.)In 2: hex(id() Out2: 0 x103b0a180In 3: a = 0 x1234In 4: hex(id(a) Out4: 0 x7f83026a395

43、0In 5: hex(id(type(a) Out5: 0 x103b0a180In 6: import sys; sys.getsizeof(a) Out6: 241.3 listtupledict sys modules sys path py I26$ cat which i#!/usr/bin/# EASY-INSTALL-ENTRY-SCRIPT: i=0.12,console_scripts,i requires = i=0.12import sysfrom pkg_resourimport load_entry_posys.exit(load_entry_po(i=0.12, c

44、onsole_scripts, i)()In 13: def test():if sys._getframe(1).f_code.co_name != a:prError!:else:prOK!:In 14: def a():test():In 15: a() OK!In 16: def b():test():In 17: b()Error! C ():Modules/main c Embeddingin Another Application27#include main(argc, char *argv)Py_Main(argc, char *argv)/ . ./ Py_Initiali

45、ze();. ./ if (d) / hon -c cmdsts = PyRun_SimpleStringFlags(d, &cf) != 0;. else if (module) / hon -m mod sts = RunModule(module, 1);.else / if (filename = NULL & stdin_is_eractive) .RunStartupFile(&cf);. ./ py sts = PyRun_AnyFileExFlags( fp,filename = NULL ? : filename,filename != NULL, &cf) != 0;. .

46、Py_Finalize();. .Py_Initialize() 是我們跟蹤的第一號(hào)目標(biāo),在這里 Python 完成了幾乎全部的初始化工作。Python/pythonrun c28void Py_Initialize(void)Py_InitializeEx(1);void Py_InitializeEx(int install_sigs)./ 解釋器狀態(tài)對(duì)象interp = PyInterpreterState_New();./ 線程狀態(tài)對(duì)象tstate = PyThreadState_New(interp);/ 創(chuàng)建所有的內(nèi)置類型對(duì)象_Py_ReadyTypes();/ 這些特殊的家伙有些

47、小秘密需要照顧一下if (!_PyFrame_Init()Py_FatalError(Py_Initialize: cant init frames);if (!_PyInt_Init()Py_FatalError(Py_Initialize: cant init ints);if (!_PyLong_Init()Py_FatalError(Py_Initialize: cant init longs);if (!PyByteArray_Init()Py_FatalError(Py_Initialize: cant init bytearray);_PyFloat_Init();/ 為解釋器對(duì)

48、象屬性分配內(nèi)存。interp-modules = PyDict_New();interp-modules_reloading = PyDict_New();/ 創(chuàng)建 builtin 模塊bimod = _PyBuiltin_Init();interp-builtins = PyModule_GetDict(bimod);Py_Initialize();PyRun_SimpleString(from time import time,ctimenprint Today is,ctime(time()n);Py_Finalize(); return 0; Py_Main Py_Initialize

49、Ex Py_InitializeExhon : _builtin_syssite1.3.1 SPyereterSe _builtin_sys modules /pyse c29PyreterSe * PyreterSe_New(void)PyreterSe *= (PyreterSe *)malloc(sizeof(PyreterSe);/ sys sysmod = _PySys_Init();-sysdict = PyModule_GetDict(sysmod);/ sys.path site-packages PySys_SetPath(Py_GetPath();/ sys.modules

50、 PyDict_SetItemString(-sysdict, modules,-modules);/ _PyImport_Init();. ./ Exception_PyExc_Init();. ._PyImportHooks_Init();/ main module initmain(); /* Module main */./ site module if (!Py_NoSiteFlag)initsite(); /* Module site */. . PyThreadSe StackFrame TraceBack /pyse c PyreterSe PyThreadSe ProsThr

51、ead 30PyThreadSe * PyThreadSe_New(PyreterSe *)return new_threadse(, 1);sic PyThreadSe * new_threadse(PyreterSe *,init)PyThreadSe *tse = (PyThreadSe *)malloc(sizeof(PyThreadSe);if (_PyThreadSe_GetFrame = NULL)_PyThreadSe_GetFrame = threadse_getframe;if (tse != NULL) tse-=;tse-frame = NULL;tse-recur_d

52、epth = 0;.tse-exc_type = NULL; tse-exc_value = NULL;tse-exc_traceback = NULL;. .return tse;if (!= NULL) HEAD_INIT();. .-modules = NULL;-modules_reloading = NULL;-sysdict = NULL;-builtins = NULL;. .return;1.3.2 Types_Py_ReadyTypes 函數(shù)完成了所有內(nèi)置類型對(duì)象初始化工作。只有準(zhǔn)備好了這些類型 (Type) 對(duì)象,我們才能創(chuàng)建對(duì)象實(shí)例 (instance)。Objects/

53、object c要 準(zhǔn)備 好一個(gè)類型對(duì)象都需要做些什么?Objects/typeobject c31int PyType_Ready(PyTypeObject *type). ./ 初始化 base object base = type-tp_base;.bases = type-tp_bases;/ 初始化 type. dict ,用于存儲(chǔ)類成員。 dict = type-tp_dict;/ 添加基本的類型成員,包括操作符、方法等。if (add_operators(type) tp_methods != NULL) if (add_methods(type, type-tp_methods

54、) tp_members != NULL) if (add_members(type, type-tp_members) tp_getset != NULL) if (add_getset(type, type-tp_getset) 0) goto error;void _Py_ReadyTypes(void)if (PyType_Ready(&PyType_Type) 0) Py_FatalError(Cant initialize type type);if (PyType_Ready(&PyBool_Type) 0) Py_FatalError(Cant initialize bool

55、type);if (PyType_Ready(&PyString_Type) 0) Py_FatalError(Cant initialize str type);. .Python PyObjects/object c -5, 257) 32#define NSMALLS257#define NSMALLNEGS5_Py_Init(void)/ . .for (ival = -NSMALLNEGS; ival ob_ival = ival;small_sival + NSMALLNEGS = v;return 1;/ mro (Method Resolution Order) if (mro

56、_ernal(type) tp_dict, doc ) = NULL) . . ./ subclass bases = type-tp_bases;n = PyTuple_GET_SIZE(bases); for (i = 0; i n; i+) PyObject *b = PyTuple_GET_ITEM(bases, i); if (PyType_Check(b) &add_subclass(PyTypeObject *)b, type) md_dict = PyDict_New();if (PyDict_SetItemString(m-md_dict, name , nameobj) !

57、= 0) goto fail;if (PyDict_SetItemString(m-md_dict, doc , Py_e) != 0) goto fail;if (PyDict_SetItemString(m-md_dict, package , Py_e) != 0) goto fail;. .if (m = PyDict_GetItemString(modules, name) != NULL & PyModule_Check(m) return m;/ m = PyModule_New(name);if (m = NULL) return NULL;/ sys.modulesif (P

58、yDict_SetItemString(modules, name, m) != 0) Py_DECREF(m);return NULL;Py_DECREF(m); /* Yes, it still exists,odules! */return m;PyObject * PyImport_GetModuleDict(void)PyreterSe *= PyThreadSe_GET()-; if (-modules = NULL)Py_FatalError(PyImport_GetModuleDict: no module dictionary!); return-modules;/sysmo

59、dule c/ sys module sic PyMethodDef sys_methods = . .displayhook,exc_info,exc_clear,excepthook,exit,. .getrefcount,sys_displayhook, METH_O, displayhook_doc, sys_exc_info, METH_NOARGS, exc_info_doc, sys_exc_clear, METH_NOARGS, exc_clear_doc, sys_excepthook, METH_VARARGS, excepthook_doc,sys_exit, METH_

60、VARARGS, exit_doc,(PyCFunction)sys_getrefcount, METH_O, getrefcount_doc,_getframe, sys_getframe, METH_VARARGS, getframe_doc,. .;/ sys. doc PyDoc_VAR(sys_doc) =.This module provides acs to some objects used or maained by thenreter and to functionsteract strongly with thereter.nnDynamic objects:n.PyOb

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論