zoukankan      html  css  js  c++  java
  • 面向对象方法小练习

    定义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方法用来从文件中反序列化出对象

    import uuid
    import settings
    import pickle
    import os
    class MySQL:
        def __init__(self,host,port):
            self.id=self.create_id()
            self.host=host
            self.port=port
        def save(self):
            if not self.is_exists:
                raise PermissionError('对象已存在')
            file_path=r'%s%s%s'%(settings.DB_PATH,os.sep,self.id)#os.sep是系统文件分隔符
            pickle.dump(self,open(file_path,'wb'))
        @property
        def is_exists(self):
            tag=True
            files=os.listdir(settings.DB_PATH)
            for file in files:
                file_abspath=r'%s%s%s'%(settings.DB_PATH,os.sep,file)
                obj=pickle.load(open(file_abspath,'rb'))
                if self.host==obj.host and self.port==obj.port:
                    tag=False
                    break
            return tag
        @classmethod
        def from_from(cls):
            return cls(settings.HOST,settings.PORT)
        @staticmethod
        def get_by_obj_id(id):
            file_abspath=r'%s%s%s'%(settings.DB_PATH,os.sep,id)
            return pickle.load(open(file_abspath,'rb'))
        @staticmethod
        def create_id():
            return str(uuid.uuid1())
    
    
    m1=MySQL.from_from()
    print(m1.get_by_obj_id('fd60ddf0-b329-11e8-957e-68ecc543ecdf').host)
    
    
    m2=MySQL('172.16.97.3','8000')
    print(m2.get_by_obj_id('96874f68-b32a-11e8-b54f-68ecc543ecdf').host)
    MySQL

    文本内容:settings.py

    HOST='127.0.0.1'
    PORT=3306
    DB_PATH=r'D:mypythonprojects基础练习db'
    

      

  • 相关阅读:
    我的第一个作业
    团队任务3:第一次冲刺
    课后作业3:个人项目(词频统计及其效能分析)
    课后作业2:个人项目
    一切的开始,从未有过的改变——课后作业1:准备
    Fiddler 添加IP显示、响应时间功能
    Jmeter所有结果分析
    云盘资源爬取利器 fmv
    python 中的 sys , os 模块用法总结
    Python 编写登录接口
  • 原文地址:https://www.cnblogs.com/happyfei/p/9613249.html
Copyright © 2011-2022 走看看