python学习2
關(guān)于反斜杠:
\ 和c++上差不多,都是繼續(xù)上一行
關(guān)于賦值:
多元賦值,x,y,z=1,2,'hello world'
///x = 1, y = 2, z = 'hello world'
關(guān)于交換:
x=1,y=2
x,y = y,x
/// y=1,x=2
python一個(gè)簡(jiǎn)單的模板:
#!/usr/bin/env python "this is a class module"import sysdebug = Trueclass Test:"Test class"passdef test():"test function"foo = Test()if debug:print "ran test()"if __name__ == "__main__": #"__main__" is ok, but " __main__ " is not ok, no space in the """main function"test()關(guān)于python的內(nèi)存管理:
變量無(wú)需聲明
變量類(lèi)型運(yùn)行時(shí)確定,并且動(dòng)態(tài)改變類(lèi)型
程序員無(wú)需關(guān)心內(nèi)存管理,和java有點(diǎn)類(lèi)似,這點(diǎn)應(yīng)該是通過(guò)引用計(jì)數(shù)器原則釋放內(nèi)存
del 語(yǔ)句能夠夠直接釋放資源; ? ? #del obj1
關(guān)于python創(chuàng)建文件:
創(chuàng)建一個(gè)文件,如何文件存在則返回,如果不存在,將list中的元素按行寫(xiě)入文件
在這個(gè)py程序中我用了函數(shù)是編程的思想,閉包的運(yùn)用
#!/usr/bin/env pythonimport osdef create_file(file = None):if os.path.exists(file) == True: //如果文件已經(jīng)存在,則返回falsereturn Falsefs = open(file,'w') //open打開(kāi)文件時(shí),如果以只寫(xiě)模式打開(kāi)文件,如果文件不存在會(huì)自動(dòng)創(chuàng)建文件def write_file(line): //按行寫(xiě)入文件,當(dāng)然得在寫(xiě)入的字符串后添加\nfs.writelines(line)return write_file //返回函數(shù)對(duì)象,寫(xiě)入一行if __name__ == "__main__":fun = create_file("/root/Desktop/hello.txt")if fun == False:print "file is already exist"else:doc = ["hello world\n","hello Alex\n","hello clare\n","hello clton\n"]for line in doc:fun(line)以上采用的函數(shù)式編程的思想,將函數(shù)當(dāng)做普通的類(lèi)型來(lái)使用,可作為返回值,也可作為參數(shù),作為變量...
以上的程序可以這么擴(kuò)展,
比如:
def operate_file(file = None, operator = 0):def 打開(kāi)文件def 寫(xiě)文件def 讀文件。。。各種各樣的操作文件的方式通過(guò)operator的值來(lái)返回不同操作問(wèn)價(jià)的函數(shù),這就是函數(shù)式編程的思想之一具體代碼如下:當(dāng)函數(shù)變?yōu)閷?duì)象,將控制流封裝在函數(shù)內(nèi)部,不同的初始化由函數(shù)參數(shù)決定,返回不同的實(shí)例化,即控制流,這將多么強(qiáng)大。
#!/usr/bin/env pythondef operator_file(file = None, operator = 0):def read_file():fs = open(file,'r')for line in fs:print linedef write_file_from_start():fs = open(file,'w')l1 = ["hello 1\n","hello 2\n","hello 3\n","hello 4\n"]for line in l1:fs.write(line)def write_file_from_end():fs = open(file,'a')l1 = ["hello 5\n","hello 6\n","hello 7\n","hello 8\n"]for line in l1:fs.write(line)dict = {0:read_file, 1: write_file_from_start , 2:write_file_from_end }return dict[operator]if __name__ == "__main__":readFile = operator_file("/root/Desktop/hello.txt",0)readFile()writeFileFromStart = operator_file("/root/Desktop/hello.txt",1)writeFileFromStart()writeFileFromEnd = operator_file("/root/Desktop/hello.txt",2)writeFileFromEnd()文件初始化為:
運(yùn)行腳本后:
?
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/GODYCA/archive/2013/01/21/2869913.html
總結(jié)
- 上一篇: unity3d 鼠标事件穿透GUI的处理
- 下一篇: websocket python爬虫_p