python学习2
關于反斜杠:
\ 和c++上差不多,都是繼續上一行
關于賦值:
多元賦值,x,y,z=1,2,'hello world'
///x = 1, y = 2, z = 'hello world'
關于交換:
x=1,y=2
x,y = y,x
/// y=1,x=2
python一個簡單的模板:
#!/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()關于python的內存管理:
變量無需聲明
變量類型運行時確定,并且動態改變類型
程序員無需關心內存管理,和java有點類似,這點應該是通過引用計數器原則釋放內存
del 語句能夠夠直接釋放資源; ? ? #del obj1
關于python創建文件:
創建一個文件,如何文件存在則返回,如果不存在,將list中的元素按行寫入文件
在這個py程序中我用了函數是編程的思想,閉包的運用
#!/usr/bin/env pythonimport osdef create_file(file = None):if os.path.exists(file) == True: //如果文件已經存在,則返回falsereturn Falsefs = open(file,'w') //open打開文件時,如果以只寫模式打開文件,如果文件不存在會自動創建文件def write_file(line): //按行寫入文件,當然得在寫入的字符串后添加\nfs.writelines(line)return write_file //返回函數對象,寫入一行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)以上采用的函數式編程的思想,將函數當做普通的類型來使用,可作為返回值,也可作為參數,作為變量...
以上的程序可以這么擴展,
比如:
def operate_file(file = None, operator = 0):def 打開文件def 寫文件def 讀文件。。。各種各樣的操作文件的方式通過operator的值來返回不同操作問價的函數,這就是函數式編程的思想之一具體代碼如下:當函數變為對象,將控制流封裝在函數內部,不同的初始化由函數參數決定,返回不同的實例化,即控制流,這將多么強大。
#!/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()文件初始化為:
運行腳本后:
?
?
?
轉載于:https://www.cnblogs.com/GODYCA/archive/2013/01/21/2869913.html
總結
- 上一篇: unity3d 鼠标事件穿透GUI的处理
- 下一篇: python中常用的函数