面向对象联系(定义mysql类)

练习1:定义MySQL类

要求:

1.对象有id、host、port三个属性

2.定义工具create_id,在实例化时为每个对象随机生成id,保证id唯一

3.提供两种实例化方式,方式一:用户传入host和port 方式二:从配置文件中读取host和port进行实例化

4.为对象定制方法,save和get_obj_by_id,save能自动将对象序列化到文件中,文件路径为配置文件中DB_PATH,文件名为id号,保存之前验证对象是否已经存在,若存在则抛出异常,;get_obj_by_id方法用来从文件中反序列化出对象

 

# -*- coding: utf-8 -*-import timeimport hashlibimport jsonimport timeimport sysimport osFILE = user_info.jsondef user(): return json.load(open(FILE))user_info = user()class Mysql: def __init__(self,host,port): self.host = host self.port = port self.id = Mysql.create_id(self) def create_id(self): m = hashlib.md5(str(time.clock()).encode(utf-8)) self.id = m.hexdigest() return m.hexdigest() def save(self): for root, dirs, files in os.walk(os.path.dirname(__file__)): if self.id in files: raise FileNotFoundError(文件已存在) json.dump(self.__dict__,open(self.id,w,encoding=utf-8)) def get_obj_by_id(self,id): dic1 = json.load(open(id)) print(dic1)stu1 = Mysql(127.0.0.1,3306)print(stu1.id,stu1.host,stu1.port)stu1.get_obj_by_id(f0fbad80768437dfabc5050e0ebd4504)stu1.save()stu2 = Mysql(user_info[host],user_info[port])#print(stu2.id,stu2.host,stu2.port)stu2.save()#输出Traceback (most recent call last):30565a8911a6bb487e3745c0ea3c8224 127.0.0.1 3306 File "G:/python练习/网络编程/class_练习题.py", line 36, in <module> stu1.save(){host: 127.0.0.1, port: 3306, id: f0fbad80768437dfabc5050e0ebd4504} File "G:/python练习/网络编程/class_练习题.py", line 26, in save raise FileNotFoundError(文件已存在)FileNotFoundError: 文件已存在

 

相关文章