day 21 作业
2024-08-31 23:07:25
定义MySQL类
- 对象有id、host、port三个属性
- 定义工具create_id,在实例化时为每个对象随机生成id,保证id唯一
- 提供两种实例化方式,方式一:用户传入host和port 方式二:从配置文件中读取host和port进行实例化
- 为对象定制方法,save和get_obj_by_id,save能自动将对象序列化到文件中,文件路径为配置文件中 DB_PATH,文件名为id号,保存之前验证对象是否已经存在,若存在则抛出异常,get_obj_by_id方法用来从文件中反序列化出对象
Copyfrom conf import settings
import uuid
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 self.is_exists:
raise PermissionError('对象已存在')
file_path = f'{settings.DB_PATH}{os.sep}{self.id}'
pickle.dump(self, open(file_path, 'wb'))
@property
def is_exists(self):
tag = False
files = os.listdir(settings.DB_PATH)
for file in files:
file_abspath = f'{settings.DB_PATH}{os.sep}{file}'
obj = pickle.load(open(file_abspath, 'rb'))
if self.host == obj.host and self.port == obj.port:
tag = True
break
return tag
@staticmethod
def get_obj_by_id(id):
file_path = f'{settings.DB_PATH}{os.sep}{id}'
return pickle.load(open(file_path, 'rb'))
@staticmethod
def create_id():
return str(uuid.uuid1())
@classmethod
def from_conf(cls):
print(cls)
return cls(settings.HOST, settings.PORT)
# conn = MySQL.from_conf()
# conn.save()
obj = MySQL.get_obj_by_id('504ab0f6-ec21-11e9-b9e2-d053497faa26')
print(obj.host)
定义一个类:圆形,该类有半径,周长,面积等属性,将半径隐藏起来,将周长与面积开放
Copyfrom math import pi
class Round:
def __init__(self, radius):
self.__radius = radius
def perimeter(self):
return round(2 * pi * self.__radius, 2)
def area(self):
return round(pi * (self.__radius ** 2), 2)
r = Round(1)
print(r.area())
print(r.perimeter())
print(r._Round__radius)
使用abc模块定义一个phone抽象类 并编写一个具体的实现类
Copyimport abc
# 抽象类/父类
class CellPhone(metaclass=abc.ABCMeta):
@abc.abstractmethod
def calling(self):
pass
@abc.abstractmethod
def send_msg(self):
pass
# 现实类/子类
class SmartPhone(CellPhone):
def calling(self):
print('calling...')
# def send_msg(self):
# print('sending msg...')
def app_download(self):
print('downloading app...')
iphone = SmartPhone()
iphone.calling()
iphone.send_msg()
iphone.app_download()
最新文章
- UIButton无法响应点击事件
- linux kernel elv_queue_empty野指针访问内核故障定位与解决
- NHibernate代码监视
- kattle 发送post请求
- 4Web Service中的几个重要术语
- mysql 自连接
- linux RTC 驱动模型分析【转】
- webservice 地址
- BT5之配置笔记
- Rose
- Leetcode:minimum_depth_of_binary_tree解决问题的方法
- Fastify 系列教程一(路由和日志)
- 【Android应用开发】EasyDialog 源码解析
- Spring MVC “404 Not Found”错误的解决
- jenkins安装部署全过程
- 轮播图js编写
- linux文件管理之查找
- php图片上传base64数据编码。
- appium+python自动化测试
- iOS:给图片置灰色