1、写一个类,有个name属性,如果name赋值为非字符串,就不让放
class Fun(): def __init__(self,name,age,male): self.name = name self.age = age self.male = male def __setattr__(self, key, value): if key == "name": if isinstance(value,str): super.__setattr__(self, key, value) else: print("不能赋值非字符串类型") else: super.__setattr__(self, key, value) def __getattr__(self, item): print("加点取值会调用我") print(type(self.__dict__),self.__dict__) return self.__dict__.get(item) fun = Fun("lxx",18,"male") fun.name = 13 print(fun.age)
2 通过上下文管理器写一个mysql的连接,通过with管理
import pymysql class Mysql: def __enter__(self): print("我在with管理的时候,会触发") print('进入with语句块时执行此方法,此方法如果有返回值会赋值给as声明的变量') # 链接 self.conn = pymysql.connect( host='127.0.0.1', port=3306, user='root', password='123456', database='book_user', charset='utf8', ) # 游标 self.cursor = self.conn.cursor() # 执行完毕返回的结果集默认以元组显示 return self def __exit__(self, exc_type, exc_val, exc_tb): self.cursor.close() self.conn.close() print('退出with代码块时执行此方法') # print('1', exc_type) # print('2', exc_val) # print('3', exc_tb) with Mysql() as self: # 这句话执行,会触发类的__enter__ print(self) sql = 'select * from app01_book;' rows = self.cursor.execute(sql) print(rows)
3 使用django实现token功能