zoukankan      html  css  js  c++  java
  • 组合,访问限制机制,抽象类 --- 练习

    1、定义MySQL类(参考答案:http://www.cnblogs.com/linhaifeng/articles/7341177.html#_label5)

    (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 hashlib
    import os
    from conf import settings
    import pickle
    
    class MySQL:
        def __init__(self,host,port):
            self.host = host
            self.port = port
            self.id = self.create_id()
    
        def create_id(self):
            res = str(self.host)+str(self.port)
            m = hashlib.md5()
            m.update(res.encode('utf-8'))
            self.id = m.hexdigest()
    
        def save(self):
            # 先配置文件路径
            file_path = os.path.join(settings.DB_PATH,f'{self.id}.pkl')
            if os.path.exists(file_path):
                raise ('文件已存在')
            else:
                with open(file_path,'wb') as fw:
                    pickle.dump(self,fw)
    
        def set_obj_by_id(self):
            file_path = os.path.join(settings.DB_PATH,f'{id}.pkl')
            with open('file_path','rb') as fr:
                res = pickle.load(fr)
                return res
            
    # 实例化方法1:
    def get_obj_1:
        host = input('host:').strip()
        port = input('port:').strip()
        return MySQL(host,port)
    
    # 实例化方法2:
    def get_obj_2:
        host = settings.host
        port = settings.port
        return MySQL(host,port)
    

    2、定义一个类:圆形,该类有半径,周长,面积等属性,将半径隐藏起来,将周长与面积开放
    参考答案(http://www.cnblogs.com/linhaifeng/articles/7340801.html#_label4)

    class Circle:
        def __init__(self,R):
            self.__R = R
            self.C = 2 * 3.14 * R
            self.S = 3.14 * R * R
    

    3、使用abc模块定义一个phone抽象类 并编写一个具体的实现类

    import abc
    class Phone(metaclass=abc.ABCMeta):
    
        @abc.abstractmethod
        def remind(self):
            pass
    
    class PhoneSun(Phone):
        def __init__(self,a,b):
            self.a = a
            self.b = b
    
        def remind(self):
            if 'a' >= 'b':
                print('音量提升')
            else:
                print('音量下降')
    
    
    # 实例化
    res = PhoneSun('a', 'b')
    return res.remind()
    
  • 相关阅读:
    Struts2标签库
    ognl表达式
    Struts2拦截器
    Struts2文件上传与下载
    Swoft2.x 小白学习笔记 (四) --- RPC
    Swoft2.x 小白学习笔记 (三) --- Task、协程
    Swoft2.x 小白学习笔记 (二) --- mysql、redis
    Swoft2.x 小白学习笔记 (一) ---控制器
    Tornado WebSocket简单聊天
    用python实现的21点游戏
  • 原文地址:https://www.cnblogs.com/whkzm/p/11657067.html
Copyright © 2011-2022 走看看