反射 :能有效减少if判断次数(我的理解)
hasattr(obj,name_string)判断一个对象是否有对应的字符串的方法
getattr(obj,name_string)根据字符串获取obj对象里对应方法的内存地址
Setattr(obj,name_string,你要设置的方法名或者静态属性)
任意设置你要调用的方法,
例子里输入eat输出
NiuHanYang is eating。。
输入bulk输出
NiuHanYang is yelling…
1 | def bulk(self): |
异常处理:已经预料到会出这种错误,不想让用户看到捕捉这个错误。
1 | try: |
Finally:不管有没有错误都执行
Except exception 抓住所有错误(缩进错误语法错误无法抓住),不建议一开始就使用,因为无法定位错误类型
可以用在后面。
1 | names = ["wch","hcd"] |
多个错误放在一起处理1
2
3
4
5
6
7
8names = ["wch","hcd"]
data = {}
try:
names[3]
data["name"]
except (KeyError,IndexError) as e:
print("没有这个key %s"%e) #当有两个错误时他会直接跳到第一个错误except语句并结束
Exception 自动抓住大多数错误
1 | names = ["wch","hcd"] |
你可以自定义异常 通过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")