python第七周:反射、异常
1.反射:
1.1定义:通过字符串映射或修改程序运行时的状态、属性、方法
1.2有以下四个方法:
(1)hasattr(object,str) 判断object对象中是否有对应的方法或属性,返回值:True·、False
class People(object):
'''this is the description of People'''
def __init__(self,name,sex,age):
self.name = name
self.sex = sex
self.age = age
def eat(self):
print("%s is eating...."%self.name)
def piao(self):
print("%s is piaoing..."%self.name)
def __call__(self, *args, **kwargs):
print("My name is Mr Wu")
def __str__(self):
return "hello world" man = People("dog","male",19)
if hasattr(man,"name") and hasattr(man,"eat"):
print("hello world!")
#output:hello world!
(2)func = getattr(object,str)根据str去获取object对象中的对应的方法的内存地址或属性的值(调用:func(argument))
class People(object):
'''this is the description of People'''
def __init__(self,name,sex,age):
self.name = name
self.sex = sex
self.age = age
def eat(self):
print("%s is eating...."%self.name)
def piao(self):
print("%s is piaoing..."%self.name)
def __call__(self, *args, **kwargs):
print("My name is Mr Wu")
def __str__(self):
return "hello world" man = People("dog","male",19)
func = getattr(man,"eat")
func() #dog is eating....
name = getattr(man,"name")
print(name) #dog
(3)delattr(object,str) 删除object对象中的str对应的方法或属性
class People(object):
'''this is the description of People'''
def __init__(self,name,sex,age):
self.name = name
self.sex = sex
self.age = age
def eat(self):
print("%s is eating...."%self.name)
def piao(self):
print("%s is piaoing..."%self.name)
def __call__(self, *args, **kwargs):
print("My name is Mr Wu")
def __str__(self):
return "hello world" man = People("dog","male",19)
delattr(man,"name")
print(man.name) #AttributeError: 'People' object has no attribute 'name'
delattr(man,"eat")
man.eat()#AttributeError: eat
(4)setattr(x,y,v)相当于x.y = v,设置新的属性或方法(可修改原有的属性和方法)
class People(object):
'''this is the description of People'''
def __init__(self,name,sex,age):
self.name = name
self.sex = sex
self.age = age
def eat(self):
print("%s is eating...."%self.name)
def piao(self):
print("%s is piaoing..."%self.name) def sleep(self):
print("%s is sleeping...."%(self.name))
name = "Mr Wu" man = People("dog","male",19)
setattr(man,"sleep",sleep)
man.sleep(man) #dog is sleeping....
setattr(man,"name",name)
print(man.name) #Mr Wu
2.异常处理
2.1 概述:
Python的异常处理能力是很强大的,可向用户准确反馈出错信息。在Python中,异常也是对象,可对它进行操作。所有异常都是基类Exception的成员。所有异常都从基类Exception继承,而且都在exceptions模块中定义。Python自动将所有异常名称放在内建命名空间中,所以程序不必导入exceptions模块即可使用异常。一旦引发而且没有捕捉SystemExit异常,程序执行就会终止。如果交互式会话遇到一个未被捕捉的SystemExit异常,会话就会终止。
2.2 python中所有的标准异常类



2.2 语法格式
try:
代码块
except 异常名称 as e:
print(e) #输出异常的内容
except 异常名称 as e:
print(e) #输出异常处理
...............
特别地:
except Exception as e:
#如果不知道异常具体是什么类型,可以使用Exception
else:
#如果没有出现前面的异常则执行这条语句
finally:
#不管有没有出现前面的异常都会执行这条语句
注:如果已经捕获到了try下的一条异常,那么就不会再捕获其他异常了
代码实例:
names = ["Mr Wu","Ms Li"]
dict_names = {"name":"Mr Wu","age":19}
try:
print(names[3])
dict_names["Mr Wang"]
except IndexError as e:
print("出错了:",e)
except KeyError as e:
print("出错了:",e)
except Exception as e:
print("未知错误:",e)
#output:出错了: list index out of range
names = ["Mr Wu","Ms Li"]
dict_names = {"name":"Mr Wu","age":19}
try:
print(names[3])
dict_names["Mr Wang"]
#except IndexError as e:
# print("出错了:",e)
#except KeyError as e:
# print("出错了:",e)
except Exception as e:
print("未知错误:",e)
#output:未知错误: list index out of range
2.3 自定义异常
我们可以自己定义异常类,并且触发执行这个异常。
注:自定义的异常必须继承异常类基类Exception,并通过raise语句实例化这个类
class AlexException(Exception):
def __init__(self,msg):
self.message = msg
try:
raise AlexException("\033[1;41m数据库连接失败\033[0m")
except AlexException as e:
print(e)
#output:数据库连接失败
python第七周:反射、异常的更多相关文章
- 从零开始学Python第七周:面向对象进阶(需修改)
一,类的属性 (1)示例 通过属性获取已经创建对象的个数 class Plane: pCount = 0 #类属性 def __init__(self,name,category): self.nam ...
- 2003031121——浦娟——Python数据分析第七周作业——MySQL的安装及使用
项目 要求 课程班级博客链接 20级数据班(本) 作业要求链接 Python第七周作业 博客名称 2003031121--浦娟--Python数据分析第七周作业--MySQL的安装及使用 要求 每道题 ...
- python金牌班第七周周末总结
python金牌班第七周周末总结 面向对象前戏 1.我们在学习面相对像之前有一个推导过程如何将我们之前写的东西,从一串代码转向给对象服务. 2.实例 我们首先模拟了两个物种进行战斗的场景,然后我们发现 ...
- 简学Python第七章__class面向对象高级用法与反射
Python第七章__class面向对象高级用法与反射 欢迎加入Linux_Python学习群 群号:478616847 目录: Python中关于oop的常用术语 类的特殊方法 元类 反射 一.P ...
- 201871010132-张潇潇-《面向对象程序设计(java)》第六-七周学习总结
201871010132-张潇潇-<面向对象程序设计(java)>第六-七周学习总结 项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh ...
- 张兴盼-201871010131 《面向对象程序设计(java)》第六、七周学习总结
张兴盼-201871010131 <面向对象程序设计(java)>第六.七周学习总结 项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh ...
- 201521123072《java程序设计》第七周总结
201521123072<java程序设计>第七周总结 标签: java 1. 本周学习总结 2. 书面作业 ArrayList代码分析 1.1 解释ArrayList的contains源 ...
- 201521123122 《java程序设计》第七周学习总结
201521123122 <java程序设计>第七周实验总结 1. 本周学习总结 以你喜欢的方式(思维导图或其他)归纳总结集合相关内容. 2. 书面作业 ArrayList代码分析 1.1 ...
- bug终结者 团队作业第六、七周
bug终结者 团队作业第六.七周 作业要求:团队作业第六.七周 博客编辑:20162322 朱娅霖 一.修改<需求规格说明书> <需求规格说明书>2.0版(即初稿) <需 ...
随机推荐
- HDU 3104 Combination Lock(数学题)
题目链接:http://acm.hdu.edu.cn/showproblem.php? pid=3104 Problem Description A combination lock consists ...
- 跟我学Java多线程——线程池与堵塞队列
前言 上一篇文章中我们将ThreadPoolExecutor进行了深入的学习和介绍,实际上我们在项目中应用的时候非常少有直接应用ThreadPoolExecutor来创建线程池的.在jdk的api中有 ...
- POJ2230题解
题目来源 id=2230">http://poj.org/problem?id=2230 题目大意 求无向图从起点1開始从不同方向经过全部边的一条路径.输出随意一条. 题解 把无向图的 ...
- Mysql db
hibernate中dialect的讲解 RDBMS方言 DB2 org.hibernate.dialect.DB2Dialect DB2 AS/400 org.hibernate.dialect.D ...
- 网页设计——Dreamweaver
在看ASP.NET视频时,讲到了一款编写HTML代码的软件--Dreamweaver.它是一款专门进行网页设置的软件.通过它能够设计出多彩的界面,相对于vs中自带的设计方式来说,他不须要知道太多的技术 ...
- nyoj--252--01串(水题)
01串 时间限制:1000 ms | 内存限制:65535 KB 难度:2 描述 ACM的zyc在研究01串,他知道某一01串的长度,但他想知道不含有"11"子串的这种长度的0 ...
- php---依赖倒转(反转控制)原则
一.简介 依赖注入和控制反转说的实际上是同一个东西,它们是一种设计模式,这种设计模式用来减少程序间的耦合 优点:使用依赖注入,最重要的一点好处就是有效的分离了对象和它所需要的外部资源,使得它们松散耦合 ...
- wpf小玩意之关键字文本框
有些时候,我们会碰到在输入文本时高亮一些文本关键字,譬如以下这图: 很明显,这个输入的文本中有四个关键字,正常文本都是黑色,关键字文本用了其他颜色.那么我们如何达到这种效果呢.wpf的textbloc ...
- 超级简单的利用javascript实现文件拖拽事件
1.效果图: 2.源码 <%@ page contentType="text/html;charset=UTF-8" language="java" %& ...
- html让图片居中显示
<div align=center><img............></div>