Python基础(11)——反射、异常处理

1、反射

以下均是对对象的操作,而不是对类

 1 class Foo(object):
 2  
 3     def __init__(self):
 4         self.name = 'wupeiqi'
 5  
 6     def func(self):
 7         return 'func'
 8  
 9 obj = Foo()
10  
11 # #### 检查是否含有成员 ####
12 hasattr(obj, 'name')
13 hasattr(obj, 'func')
14  
15 # #### 获取类内与名称一样的成员地址 ####
16 getattr(obj, 'name')
17 getattr(obj, 'func')
18  
19 # #### 设置成员 ####把类外的方法(函数)放到类内
20 setattr(obj, 'age', 18)
21 setattr(obj, 'show', lambda num: num + 1)
22  
23 # #### 删除成员 ####
24 delattr(obj, 'name')
25 delattr(obj, 'func')
26 
27 反射代码示例
 1 def bulk(self):
 2     print("%s is yelling...." %self.name)
 3 
 4 class Dog(object):
 5     def __init__(self,name):
 6         self.name = name
 7 
 8     def eat(self,food):
 9         print("%s is eating..."%self.name,food)
10 
11 
12 d = Dog("NiuHanYang")
13 choice = input(">>:").strip()
14 
15 if hasattr(d,choice):
16     getattr(d,choice)#d.choice
17 else:
18     setattr(d,choice,bulk) #d.talk = bulk#在对象中添加了choice输入内容的方法(函数)
19     func = getattr(d, choice)
20     func(d)

2、异常处理

1 #执行内容1,当1出错是,执行内容2
2 try:
3     执行内容1
4 except () as e:#把异常的内容存到e里
5     执行内容2

例子:  

1 name=[1,2,3]
2 
3 try:
4     name[3]
5 except IndexError as e:
6     print("错误原因是",e)

多异常处理

 1 try:
 2     name[3]
 3 except IndexError as e:
 4     print("错误原因是",e)
 5 except KeyError as e:
 6     print("错误原因是", e)
 7 #或者
 8 try:
 9     name[3]
10 except (KeyError,IndexError) as e:
11     print("错误原因是",e)
12 # 或者
13 try:
14     name[3]
15 except Exception as e:#抓住所有错误
16     print("出错了", e)

自定义异常:

1 class WupeiqiException(Exception):
2  
3     def __init__(self, msg):
4         self.message = msg
5  
6 try:
7     raise WupeiqiException('我的异常')#主动触发异常
8 except WupeiqiException as e:
9     print e

http://www.cnblogs.com/wupeiqi/articles/5017742.html

猜你喜欢

转载自www.cnblogs.com/long5683/p/9301938.html