Day 21 作业

作业


'''
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 uuid
import os
import pickle

'''
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方法用来从文件中反序列化出对象
'''
DB_PETH = os.path.dirname(__file__)
host = '123'
port = 80


class MySql:
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.id = self.creat_id()

    def save(self):
        file_path = os.path.join(DB_PETH, self.id)
        if not self.is_exist:
            raise PermissionError('内容已存在')
        with open(f'{file_path}.pkl', 'wb') as f:
            pickle.dump(self, f)

    @property
    def is_exist(self):
        tag = True
        files = os.listdir(DB_PETH)
        for file in files:
            if file.endswith('.pkl'):
                file_path = os.path.join(DB_PETH, file)
                obj = pickle.load(open(file_path, 'rb'))
                if obj.host == self.host and obj.port == self.port:
                    tag = False
        return tag

    def get_obj_by_id(self):
        file_path = os.path.join(DB_PETH, self.id)
        with open(f'{file_path}.pkl', 'rb') as f:
            return pickle.load(f)

    @staticmethod
    def creat_id():
        return str(uuid.uuid1())


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

class Circle:
    def __init__(self, rad):
        self.__rad = rad
    
    # 周长
    @property
    def per(self):
         return 2 * math.pi * self.__rad
    
    # 面积
    @property
    def area(self):
         return math.pi * self.__rad * self.__rad


c = Circle(5)
print(c.area)
print(c.per)

import abc

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


class Phone(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def call(self):
        pass

    @abc.abstractmethod
    def massage(self):
        pass

    def game(self):
        pass

    def music(self):
        pass

    def video(self):
        pass

原文地址:https://www.cnblogs.com/2222bai/p/11656851.html