python_oop_反射_异常处理

复制代码
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # Author:woshinidaye
 4 
 5 
 6 class Man(object):
 7     '''
 8     该类用于测试反射功能和异常处理
 9     '''
10     def __init__(self,name):
11         self.name = name
12     def eat(self):
13         print(f'{self.name} is eating...')
14     def work(self):
15         print(f'{self.name} is working...')
16 
17 def sleep(self):
18     print(f'{self.name} is sleepping...')
19 one_man = Man('woshinidaye')    #实例化一个对象
20 
21 # choice = input('one_man 你想做什么:').strip()
22 # 对于程序而言,经常需要接收用户的字符串输入,然后调用字符串的方法,但是直接one_man.choice肯定不行的,
23 # 因为one_man这个对象中压根choice这个属性
24 # 这里就需要用到反射的功能,即将用户输入的字符串作为一个功能执行
25 
26 '''
27 if hasattr(one_man,choice) is True:  #判断object这个对象中是否存在str属性,hasattr(object,str)
28     # getattr(one_man,choice)         #如果存在就执行该属性,getattr(one_man,choice)
29     # print(type(getattr(one_man,choice)))        #这是一个方法<class 'method'>,要执行的话需要添加()
30     getattr(one_man, choice)()
31 else:
32     setattr(one_man,choice,sleep)       #setattr(x, 'y', v) is equivalent to ``x.y = v''
33     print(type(getattr(one_man,choice)))        #<class 'function'>
34     getattr(one_man,choice)(one_man)     #这里传入one_man是因为我自己写的sleep函数里面传了self进去;
35 
36 '''
37 
38 
39 #还有一个反射方法是 delattr,删除
40 
41 #有时,用户的输入可能不存在,可能不合法,程序会报错,那需要接收错误,并打印一些信息
42 
43 try:
44     # one_man.shopping()
45     # int('asdf')
46     second_man = Man()
47     # int('123')
48 except AttributeError as error:  #逻辑是先执行try部分,执行不下去,就进行except处理
49     print('没有这个属性',error)
50 except ValueError as error:     #常见的错误不多,大多数错误都能接受,如果接受不到,可以用Exception
51     print('数值类型错误',error)
52 except Exception as error:
53     print('未知错误',error)
54 else:
55     print('成功了,没有报错')           #没有出错,才会执行else语句
56 finally:
57     print('别管结果怎么样,我就是要执行一次')
58 
59 print(type(Exception))
60 
61 #自定义异常
62 class My_error(Exception):          #创建类,继承Exception类
63     def __init__(self,msg):
64         self.msg = msg
65     def __str__(self):
66         return self.msg
67 try:
68     raise My_error('TCP连接失败')    #主动触发异常
69 except My_error as error:
70     print(error)
复制代码

 

posted @   woshinidaye  阅读(40)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· Qt个人项目总结 —— MySQL数据库查询与断言
历史上的今天:
2020-12-30 三、K8s的基本概念
点击右上角即可分享
微信分享提示