Exercise 1: Defining the MySQL Class
Requirements:
1. Object has ID, host, port three properties
2. Define tool create_id, randomly generate ID for each object at instantiation, guarantee ID unique
3. Provide two kinds of instantiation mode, one: User incoming host and port mode two: Read host and port from configuration file to instantiate
4. To customize the method for the object, save and Get_obj_by_id,save can automatically serialize the object to a file, the file path is db_path in the configuration file, the file name is the ID number, before saving to verify whether the object already exists, if present, throw an exception; get_obj_by_ The ID method is used to deserialize the object from the file
#-*-coding:utf-8-*-Import TimeImportHashlibImportJSONImport TimeImportSYSImportOsfile='User_info.json'defUser ():returnjson.load (Open (FILE)) User_info=User ()classMysql:def __init__(self,host,port): Self.host=host Self.port=Port Self.id=mysql.create_id (self)defcreate_id (self): M= Hashlib.md5 (str (Time.clock ()). Encode ('Utf-8')) Self.id=m.hexdigest ()returnm.hexdigest ()defSave (self): forRoot, dirs, filesinchOs.walk (Os.path.dirname (__file__)): ifSelf.idinchFiles:RaiseFilenotfounderror ('file already exists') Json.dump (self.__dict__, open (Self.id,'W', encoding='Utf-8')) defget_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 ()#OutputTraceback (most recent): 30565a8911a6bb487e3745c0ea3c8224127.0.0.1 3306File"G:/python Practice/network programming/class_ exercises. PY", Line 36,inch<module>Stu1.save () {'Host':'127.0.0.1','Port': 3306,'ID':'f0fbad80768437dfabc5050e0ebd4504'} File"G:/python Practice/network programming/class_ exercises. PY", line 26,inchSaveRaiseFilenotfounderror ('file already exists') Filenotfounderror: file already exists
Object-oriented contact (definition MySQL Class)