关于反斜杠:
\ 和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 sys debug = True class Test: "Test class" pass def 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 python import os def create_file(file = None): if os.path.exists(file) == True: //如果文件已经存在,则返回false return False fs = open(file,'w') //open打开文件时,如果以只写模式打开文件,如果文件不存在会自动创建文件 def write_file(line): //按行写入文件,当然得在写入的字符串后添加\n fs.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 python def operator_file(file = None, operator = 0): def read_file(): fs = open(file,'r') for line in fs: print line def 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()
文件初始化为:
运行脚本后: