作业(自定义异常 魔法的使用)
作业
1 写一个类,有个name属性,如果name赋值为非字符串,就不让放
class mytest: def __init__(self): pass def __setattr__(self, key, value): if type(value) is str: #判断类型进行比较 super.__setattr__(self,key,value) else: print('不是字符串不能添加') a=mytest() a.name=123 print(a.__dict__)
2 通过上下文管理器写一个mysql的连接,通过with管理
1 # 第一道 2 3 # 自定义异常 4 # class NotStrException(BaseException): 继承这个类 5 # def __init__(self,msg): 6 # self.msg=msg 传入异常的值 7 # def __str__(self): 8 # return self.msg 打印时输出填写的错误 9 # 10 # 11 # class Person(): 12 # def __setattr__(self, key, value): 13 # if isinstance(value,str): #isinstance 判断一个是不是一个类型 issubclass(myclass,classtype)判断一个类是不是另一个类的子类 14 # # setattr(self,key,value) #内部是这么执行的self.key=value 15 # # self.__dict__[key]=value 16 # object.__setattr__(self,key,value) 17 # else: 18 # # print("你不能放") 19 # raise NotStrException('不是字符串异常') 20 # 21 # person=Person() 22 # 23 # try: 24 # # person.name=99 25 # person.name='lqz' 26 # except NotStrException as e: 触发自定义异常 27 # print(e) 28 # 29 # print(person.name) 30 31 32 ## 第二道 33 # import pymysql 34 # class Mysql(): 35 # def __enter__(self): with时调用 36 # 37 # self.conn=pymysql.connect(host='127.0.0.1', user='root', password="123456", 38 # database='mytest', port=3306) 39 # return self.conn # 会被as 后的对象拿到 40 # 41 # def __exit__(self, exc_type, exc_val, exc_tb): 42 # self.conn.close() 结束时运行 43 # 44 # 45 # with Mysql() as mysql: 46 # mysql.cursor()

浙公网安备 33010602011771号