#异常处理
#假如你的程序中有一些无效的语句,会怎么样呢?Python会引发并告诉你那里有一个错误,从而处理这样的情况但会中断程序
# 那么不想中断程序,就需要捕捉这些异常就要用到异常处理
‘‘‘
try:#逻辑代码在try和except语句块间
a=[1,2,3]
a[6]
except NameError,e:#几个except只能过滤出一个错误,后面的except不会执行
print(e)
except IndexError,e:
print(e)
#raise Exception(‘错误了。。。‘) #主动触发异常,内容记录进e
except Exception,e: #Exception跳过大部分错误
print(e)
else: #主代码块执行正常执行
print ‘fvdsf‘
finally:#永远执行,逻辑代码执行完之后,在finally后的代码将不被执行
print ‘dddddddddddddddddddddddddd‘
class error(Exception):#自定义异常
def __init__(self,msg=None):
self.msg=msg
def __str__(self):
return self.msg
try:
raise error(‘自定义的异常‘)
except Exception,e:
print(e)
‘‘‘
‘‘‘
#Python的反射
#python中的反射功能是由以下四个内置函数提供:hasattr、getattr、setattr、delattr,
# 四个函数分别用于对对象内部执行:检查是否含有某成员、获取成员、设置成员、删除成员。
hasattr() #判断成员是否存在
getattr() #获取成员
delattr() #删除成员
setattr() #设置成员
‘‘‘
‘‘‘
#实例
class Foo(object):
def __init__(self):
self.name = ‘wupeiqi‘
def func(self):
return ‘func‘
obj = Foo()
print Foo.__dict__
hasattr(obj, ‘name‘)# 检查是否含有成员
getattr(obj, ‘name‘)# 获取成员
setattr(obj, ‘age‘, 18)#设置成员,临时在内存中添加成员
delattr(obj, ‘name‘)#删除成员,临时在内存中删除成员
#结论反射是通过字符串的形式操作对象相关的成员
‘‘‘
本文出自 “小波的博客” 博客,请务必保留此出处http://lxb994.blog.51cto.com/9805112/1725624
原文:http://lxb994.blog.51cto.com/9805112/1725624