Python学习笔记(3)
更新时间:2022-08-14 20:34:10
Python学习笔记(3)
1)Statements and SyntaxHash mark (#)表示Python注释NEWLINE(/n)是标准行操作符Backslash(/)表示一行继续Semicolon(;)在同一行连接两个语句Colon(:)从suite中分隔首行Suites通过缩进进行限制Python文件以模块进行组织2)Variable Assignment等号(=)是赋值操作符>>> anInt = -12>>> String = 'cart'>>> aFloat = -3.1415*(5.0**2)>>> anotherString = 'shop'+'ping'>>> aList = [3.14e10, '2nd elmt of a list', 8.82-4.371j]多个赋值>>> x,y,z = 1,2,'a string'>>> x1>>> y2>>> z'a string'例子:交换x和y的值>>> (x,y) = (5,6)>>> x5>>> y6>>> (x,y) = (y,x)>>> x6>>> y53)Identifiers有效的Python标识符: - 第一个字符必须是字母或下划线 - 其后的字符可以是字母、数字或下划线 - 大小写敏感 关键字:目前有28个关键字and elif global or assert else if passbreak except import print class exec in raisecontinue finally is return def for lambda trydel from not whileBuilt-insPython内建的都应该做关键字处理,作为系统保留对待。Python不支持标识符重载。特殊的下划线标识符Python指定了特殊的带下划线前缀或后缀的变量。_xxx 不用‘ from module import * ’ 导入_xxx__ 系统定义的名字__xxx 请求私有名4)DocumentPython提供了一个机制,文档字符串能通过__doc__特殊变量动态取回。在模块、类声明、或函数声明的第一个未赋值字符串能通过使用obj.__doc__访问,obj代表模块、类或函数名。Indentation缩进在Python中扮演了一个重要角色。缩进4个字符***,缩进代表某个块。Module Structure and Layout模块有简单的物理方式和逻辑组织。在每个文件内,应该建立一致的、易读的结构。***是按如下进行布局: -startup line 开始行 -module documentation 模块说明文档 -module import 模块导入部分 -variable declarations 变量声明 -class declarations 类声明 -function declarations 函数声明 -"main" body 模块主体部分例子:# /usr/bin/env python"this is a test module"import sysimport stringdebug = 1class FooClass: "Foo Class" passdef test(): "test function" foo = FooClass if debug: print 'ran test()'if __name__ == '__main__': test()在主体部分创建测试良好的编程习惯是为整个应用程序提供一套测试集。5)Memory Management内存管理 -变量并不提前声明 -变量类型不需声明 -在程序员部分无内存管理 -变量名可回收再用 -del语句允许清晰地重新分配一旦某数据对象不再需要时,Python的垃圾回收器会自动释放该数据对象。此行为无需编程人员操心。Python通过跟踪对象的引用数量,来决定对象是否需要。这称为“引用计算”。del语句del语句移除一对象的单个引用,其语法如下:del obj1[, obj2 [,...objN...]]例如:# 初始化string对象,设置引用数为1foo1 = 'foobar'# 通过赋值给另一变量,增加引用数foo2 = foo1 # 创建一个别名# 通过函数调用再次增加引用数check_val(foo1)# 从命名空间移除foo2;'foobar'对象的引用数减少del foo2# 移除'foobar'对象的最后一个引用,减少其引用数为0,最终导致对象变成不可访问的。del foo16)第一个Python程序#!/usr/bin/env python"fgrepwc.py -- searches for string in text file"import sysimport string# print usage and exitdef usage(): print "usage: fgrepwc [-i] string file" sys.exit(1)# does all the workdef filefind(word, filename): #reset word count count = 0 # can we open file? if so, return file handle try: fh = open(filename, 'r') # if not, exit except: print filename, ":", sys.exc_info()[1] usage() # read all file lines into list and close allLines = fh.readlines() fh.close() # iterate over all lines of file for eachLine in allLines: # search each line for the word if string.find(eachLine, word)>-1: count = count+1; print eachLine, # when complete, display line count print count #validates arguments and calls filefind()def checkargs(): # check args; 'argv' comes from 'sys' module argc = len(sys.argv) if argc != 3: usage() # call fgrepwc.filefind() with args filefind(sys.argv[1], sys.argv[2]) #execute as applicationif __name__ == '__main__': checkargs()