Python学习笔记(2)
更新时间:2022-08-14 20:39:17
Python学习笔记(2)
1)Error and Exceptions错误和异常语法错误是在编译时检查,但Python允许在程序执行期间检查错误。当检查出错误,Python解释器抛出、产生、触发一个异常。要增加错误检测或异常处理到代码,使用try-except语句。语法如下:try: try_running_this_suiteexcept suite_if_someError_occurs2)FunctionsPhthon的函数与其它编程语言相似,函数使用()操作符进行调用,函数在使用前声明,函数类型是其返回值类型。函数的参数通过引用进行调用。声明函数:def function_name([arguments]): "optional documentation string" function_suite例子:>>> def addMe2Me(x): 'apply + operation to argument' return (x+x)>>> addMe2Me(4.25)8.5>>> addMe2Me(10)20>>> addMe2Me('python ')'python python '>>> addMe2Me([-1, 'abc'])[-1, 'abc', -1, 'abc']>>> 缺省参数的例子:>>> def foo(debug=1): 'determine if in debug mode with default argument' if debug: print 'in debug mode' print 'done'>>> foo()in debug modedone>>> foo(0)done3)Classes类仅仅是保护静态数据成员或函数声明的容器,其静态数据成员或函数声明则称为类属性。类提供了创建实际对象的blueprints,创建的实际对象称为类的实例。函数在类中称为方法。声明类:class class_name[(base_classes_if_any)]: "optional documentation string" static_member_declarations method_declarations类声明使用class关键字。如声明子类,那么其超类或基类应该在圆括号中给出。>>> class FooClass: 'my very first class: FooClass' version = 0.1 # class (data) attribute def __init__(self, nm='John Doe'): 'constructor' self.name = nm # class instance (data) attribute print 'Created a class instance for', nm def showname(self): 'display instance attribute and class name' print 'Your name is', self.name print 'My name is', self.__class__ # full class name def showver(self): 'display class(static) attribute' print self.version # references FooClass.version def addMe2Me(self, x): # does not use 'self' 'apply + operation to argument' return (x+x)>>> foo1 = FooClass()Created a class instance for John Doe>>> foo1.showver()0.1>>> print foo1.addMe2Me(5)10>>> print foo1.addMe2Me('xyz')xyzxyz>>> foo1.showname()Your name is John DoeMy name is __main__.FooClass>>> foo2 = FooClass('Jane Smith')Created a class instance for Jane Smith>>> foo2.showname()Your name is Jane SmithMy name is __main__.FooClass注意:当创建一个类实例时,其__init__()方法被自动调用。4)Modules模块是一个组织多个Python代码文件的逻辑方法。模块可包含可执行的代码、函数、类或以上所有类型。模块名即为文件名,但不包括扩展名。当创建了一个模块后,使用import语句导入模块。import module_name调用模块函数:module.function()访问模块变量:module.variable例子:>>> import sys>>> sys.stdout.write('Hello World!/n')Hello World!下一个例子:>>> import sys>>> import string>>> sys.platform'win32'>>> sys.version'2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)]'>>> up2space = string.find(sys.version, ' ')>>> ver = sys.version[:up2space]>>> ver'2.5.1'>>> print 'I am running Python %s on %s' % (ver, sys.platform)I am running Python 2.5.1 on win32例3:>>> verchunks = string.split(sys.version)>>> verchunks['2.5.1', '(r251:54863,', 'Apr', '18', '2007,', '08:51:08)', '[MSC', 'v.1310', '32', 'bit', '(Intel)]']>>> print 'I am running Python %s on %s' % / (verchunks[0], sys.platform)I am running Python 2.5.1 on win32