1、定义MySQL类
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方法用来从文件中反序列化出对象
# settings.py内容
"""
DB_PATH = 'F:python12期day 21conf'
host = '114.114.114.1124'
port = 12234
"""
import pickle
import os
import hashlib
import time
import settings
class Mysql:
def __init__(self,host,port):
self.host = host
self.port = port
self.id = self.create_id()
# 创建id
def create_id(self):
id_time = str(time.time())
return hashlib.md5(id_time.encode('utf-8')).hexdigest()
# 判断文件中对象中的host和port是否和相同
@property
def id_exists(self):
files = os.listdir(settings.DB_PATH) # 列出路径中的所有文件生成列表
for file in files:
file_path = os.path.join(settings.DB_PATH, file)
with open(file_path,'rb')as fr:
obj = pickle.load(fr)
if self.host == obj.host and self.port == obj.port:
return False
return True
# 不加@classmethod的话,从配置文件调用时,需要把Mysql类名当作参数传入括号内
# @classmethod 可以将让装饰函数把类当作第一个参数传入运行
def from_settings(self):
return self(settings.host, settings.port)
def save(self):
if self.id_exists: # 这里会调用id_exists函数,返回出结果,不存在为True
is_path = os.path.join(settings.DB_PATH,self.id)
with open(is_path,'wb') as fw:
pickle.dump(self,fw)
else:
raise PermissionError('对象已存在')
# @staticmethod # 可以将被装饰函数变成全局函数,即不需要声明传入self
def get_obj_by_id(self):
id_path = os.path.join(settings.DB_PATH,self.id)
with open(id_path,'rb') as fr:
print(pickle.load(fr).__dict__)
# sql = Mysql(11221,222222)
# sql.save()
# sql.get_obj_by_id()
aa =Mysql.from_settings(Mysql)
aa.save()
aa.get_obj_by_id()
2、定义一个类:圆形,该类有半径,周长,面积等属性,将半径隐藏起来,将周长与面积开放
import math
class circle:
def __init__(self,r):
self.r = r
@property
def zhouchang(self):
return 2 * math.pi * self.r
@property
def mainji(self):
return math.pi * self.r ** 2
c = circle(5)
print(c.zhouchang)
print(c.mainji)
3.使用abc模块定义一个phone抽象类 并编写一个具体的实现类
import abc
class Phone(metaclass=abc.ABCMeta):
@abc.abstractclassmethod
def anjian(self):
pass
@abc.abstractclassmethod
def pingmu(self):
pass
@abc.abstractclassmethod
def jishen(self):
pass
@abc.abstractclassmethod
def yingjian(self):
pass
class Mi(Phone):
def anjian(self):
print('这只是按键')
def pingmu(self):
print('这只是屏幕')
def jishen(self):
print('这是机身')
def yingjian(self):
print('这是硬件')
def withdraw(self):
m.anjian()
m.jishen()
m.yingjian()
m.yingjian()
m = Mi()
m.withdraw()