day-21 作业
day 21 作业
1.
'''
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方法用来从文件中反序列化出对象
'''
# file settings.py
# HOST='127.0.0.1'
# PORT=3306
# DB_PATH=r'D:\data\python\Learn\courses\day21\作业\db'
import settings
import uuid
import pickle
import os
class MySQL:
def __init__(self, host, port):
self.id = self.creat_id
self.host = host
self.port = port
@property
def creat_id(self):
return str(uuid.uuid1())
def is_exists(self):
flag = True
files = os.listdir(settings.DB_PATH)
for file in files:
file_path = os.path.join(f'{settings.DB_PATH}', f'{file}')
with open(file_path, 'rb')as fr:
obj = pickle.load(fr)
if self.host == obj.host and self.port == obj.port:
flag = False
break
return flag
def save(self):
# 如果路径不存在,就创建一个
if not os.path.isdir(settings.DB_PATH):
os.mkdir(settings.DB_PATH)
# 拼接文件路径
file_path = os.path.join(settings.DB_PATH, f'{self.id}.pkl')
# 判断文件是否存在,存在就报错,不存在就保存
if not self.is_exists():
raise PermissionError("已存在")
with open(file_path, 'wb') as fw:
pickle.dump(self, fw)
@staticmethod
def get_obj_by_id(id):
file_path = os.path.join(settings.DB_PATH, f'{id}.pkl')
with open(file_path, 'rb')as fr:
data = pickle.load(fr)
return data
# 对应的函数不需要实例化,不需要self参数,但第一个参数需要是表示自身类的cls参数,可以来调用类的属性,类的方法,实例化对象等
@classmethod
def from_conf(cls):
return cls(settings.HOST, settings.PORT)
# 从文件中导入数据创建实例
# conn=MySQL.from_conf()
# conn.save()
#
# # 查看文件导入数据创建的示例
# data=conn.get_obj_by_id('73008cdc-ec15-11e9-b036-d46d6dd6b87e')
# print(data.__dict__)
# 传入数据创建示例
# conn1 = MySQL('127.0.0.1', 3300)
# conn1.save()
# 查看文件导入数据创建的示例
# data2=conn1.get_obj_by_id('dd8e2648-ec16-11e9-a9b4-d46d6dd6b87e')
# print(data2.__dict__)
# 传入相同数据保存时报错
# conn2 = MySQL('127.0.0.1', 3300)
# conn2.save()
2.
'''2、定义一个类:圆形,该类有半径,周长,面积等属性,将半径隐藏起来,将周长与面积开放'''
import cmath
class Circular:
def __init__(self, r, ):
self.__r = r
self.perimeter = self.perimeter()
self.area = self.area()
# 计算圆周长
def perimeter(self):
perimeter = 2 * cmath.pi * self.__r
return perimeter
# 计算圆面积
def area(self):
area = cmath.pi * (self.__r ** 2)
return area
# 获取圆半径接口
def get_r(self):
return self.__r
circular = Circular(3)
print(circular.area)
print(circular.perimeter)
print(circular.get_r())
运行结果:
28.274333882308138
18.84955592153876
3
Process finished with exit code 0
3.
'''3、使用abc模块定义一个phone抽象类 并编写一个具体的实现类'''
import abc
class Phone(metaclass=abc.ABCMeta):
@abc.abstractmethod
def game(self):
pass
@abc.abstractmethod
def music(self):
pass
@abc.abstractmethod
def read(self):
pass
class Mi(Phone):
def game(self):
pass
def music(self):
pass
def read(self):
pass
def hot(self):
pass
redmi = Mi()