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 hashlib
import os
from conf import settings
import pickle
class MySQL:
def __init__(self,host,port):
self.host = host
self.port = port
self.id = self.create_id()
def create_id(self):
res = str(self.host)+str(self.port)
m = hashlib.md5()
m.update(res.encode('utf-8'))
self.id = m.hexdigest()
def save(self):
# 先配置文件路径
file_path = os.path.join(settings.DB_PATH,f'{self.id}.pkl')
if os.path.exists(file_path):
raise ('文件已存在')
else:
with open(file_path,'wb') as fw:
pickle.dump(self,fw)
def set_obj_by_id(self):
file_path = os.path.join(settings.DB_PATH,f'{id}.pkl')
with open('file_path','rb') as fr:
res = pickle.load(fr)
return res
# 实例化方法1:
def get_obj_1:
host = input('host:').strip()
port = input('port:').strip()
return MySQL(host,port)
# 实例化方法2:
def get_obj_2:
host = settings.host
port = settings.port
return MySQL(host,port)
2、定义一个类:圆形,该类有半径,周长,面积等属性,将半径隐藏起来,将周长与面积开放
参考答案(http://www.cnblogs.com/linhaifeng/articles/7340801.html#_label4)
class Circle:
def __init__(self,R):
self.__R = R
self.C = 2 * 3.14 * R
self.S = 3.14 * R * R
3、使用abc模块定义一个phone抽象类 并编写一个具体的实现类
import abc
class Phone(metaclass=abc.ABCMeta):
@abc.abstractmethod
def remind(self):
pass
class PhoneSun(Phone):
def __init__(self,a,b):
self.a = a
self.b = b
def remind(self):
if 'a' >= 'b':
print('音量提升')
else:
print('音量下降')
# 实例化
res = PhoneSun('a', 'b')
return res.remind()