定义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()

最新文章

  1. UIButton无法响应点击事件
  2. linux kernel elv_queue_empty野指针访问内核故障定位与解决
  3. NHibernate代码监视
  4. kattle 发送post请求
  5. 4Web Service中的几个重要术语
  6. mysql 自连接
  7. linux RTC 驱动模型分析【转】
  8. webservice 地址
  9. BT5之配置笔记
  10. Rose
  11. Leetcode:minimum_depth_of_binary_tree解决问题的方法
  12. Fastify 系列教程一(路由和日志)
  13. 【Android应用开发】EasyDialog 源码解析
  14. Spring MVC “404 Not Found”错误的解决
  15. jenkins安装部署全过程
  16. 轮播图js编写
  17. linux文件管理之查找
  18. php图片上传base64数据编码。
  19. appium+python自动化测试
  20. iOS:给图片置灰色

热门文章

  1. cisco 路由与ASA SSH 设置
  2. iOS - 浮点数去掉小数点之后的0,以0.5小数递增函数
  3. mvn-dependencies-vs-dependencyManagement
  4. [数据结构 - 第3章] 线性表之单链表(C++实现)
  5. mybatis-3.5.2增删查改
  6. html中定义模板
  7. MyBatis 学习笔记(七)批量插入ExecutorType.BATCH效率对比
  8. c++11多线程记录4:死锁
  9. Go基础编程实践(七)—— 并发
  10. yii框架中的各种小问题