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方法用来从文件中反序列化出对象
import hashlib,os,json
from settings import*#导入一个配置文件
class Mysql:
def __init__(self,host,port):
self.host = host
self.port = port
def create_id(self):
m = hashlib.md5()
lt = [self.host,self.port]
id1 = ','.join(lt)
m.update(id1.encode('utf-8'))
return m.hexdigest()
def save(self):
path = os.path.join(DB_PATH, f'{self.create_id()}.json')
if not os.path.exists(path):
lt = [self.host, self.port]
with open(path,'w',encoding='utf8') as fw:
json.dump(str(self),fw)
else:
raise PermissionError ('文件已经存在')
def get_obj_by_id(self):
path = os.path.join(DB_PATH, f'{self.create_id()}.json')
if not os.path.exists(path):
raise PermissionError ('文件不存在')
with open(path,'r',encoding='utf8') as fr:
read = json.load(fr)
return read
# user1 = Mysql(host,port)
# print(user1.create_id())
user2 = Mysql('xiaoming','xiaozhan')
# print(user2.create_id())
# #settings.py内容
# #user1.save()
# user2.save()
print(user2.get_obj_by_id())
2、定义一个类:圆形,该类有半径,周长,面积等属性,将半径隐藏起来,将周长与面积开放
from math import pi
class Circle:
def __init__(self, radius):
self.__radius = radius
def area(self):
are = (self.__radius ** 2) * pi
return are
def perimeter(self):
peri = 2 * pi * self.__radius
return peri
3、使用abc模块定义一个phone抽象类 并编写一个具体的实现类
class Phone(metaclass=abc.ABCMeta):
@abc.abstractmethod
def call(self):
pass
@abc.abstractmethod
def play_game(self):
pass
@abc.abstractmethod
def witch_vedio(self):
pass
class Miphone:
def call(self):
pass
def play_game(self):
pass
def witch_vedio(self):
pass
def listen_music(self):
pass