反射和异常处理机制断言的使用

反射 :能有效减少if判断次数(我的理解)
hasattr(obj,name_string)判断一个对象是否有对应的字符串的方法
getattr(obj,name_string)根据字符串获取obj对象里对应方法的内存地址
Setattr(obj,name_string,你要设置的方法名或者静态属性)
任意设置你要调用的方法,

例子里输入eat输出
NiuHanYang is eating。。
输入bulk输出
NiuHanYang is yelling…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def bulk(self):
print("%s is yelling...." %self.name)

class Dog(object):
def __init__(self,name):
self.name = name

def eat(self,food):
print("%s is eating..."%self.name,food)


d = Dog("NiuHanYang")
choice = input(">>:").strip()
if hasattr(d,choice):
func = getattr(d,choice)
func("ChengRongHua")
else:
setattr(d,choice,bulk)
d.talk(d) #talk 是你随意指定的关联的方法名

异常处理:已经预料到会出这种错误,不想让用户看到捕捉这个错误。

1
2
3
4
5
6
try
Code
Except (error1,error2) as e:
Print e
finally:
Print ()

Finally:不管有没有错误都执行
Except exception 抓住所有错误(缩进错误语法错误无法抓住),不建议一开始就使用,因为无法定位错误类型
可以用在后面。

1
2
3
4
5
6
7
8
9
10
11
12
names = ["wch","hcd"]
data = {}
try:

names[3]
data["name"]
except KeyError as e:
print("没有这个key %s"%e) #当有两个错误时他会直接跳到第一个错误except语句并结束
except IndexError as e:
print("列表操作错误 %s"%e)
finally:
print("不管有没有错误都执行")

多个错误放在一起处理

1
2
3
4
5
6
7
8
names = ["wch","hcd"]
data = {}
try:

names[3]
data["name"]
except (KeyError,IndexError) as e:
print("没有这个key %s"%e) #当有两个错误时他会直接跳到第一个错误except语句并结束

Exception 自动抓住大多数错误

1
2
3
4
5
6
7
8
9
names = ["wch","hcd"]
data = {}
try:

# names[3]
# data["name"]
open("sc.txt")
except Exception as e: #自动抓住大多数错误
print("出错了 %s"%e)

你可以自定义异常 通过raise触发

1
2
3
4
5
6
7
8
9
10
11

# Author: Diedline
class AlexError(Exception):
def __init__(self, msg):
self.message = msg
# def __str__(self):
# return 'sdfsf'
try:
raise AlexError('数据库连不上') #raise触发
except AlexError as e:
print(e)

断言

1
2
3
4
5
6
7
8
9
10
11
12
13
#  Author: Diedline
class dog(object):
def __init__(self,food):
self.food = food
def eat(self):
print("Dog is eating %s"%self.food)

obj = dog("包子")
assert type(obj.food) is str
"""
断言 obj.food is str 为真继续执行,假抛出断言异常
"""
print("dddd")