今日作业
import uuid
import hwk_settings
import os
import pickle
class MySql:
# 1.对象有id、host、port三个属性
def __init__(self, host, port):
self.id = self.create_id()
self.host = host
self.port = port
# 2.定义工具create_id,在实例化时为每个对象随机生成id,保证id唯一
def create_id(self):
id = uuid.uuid1()
return str(id)
# 3.提供两种实例化方式,方式一:用户传入host和port 方式二:从配置文件中读取host和port进行实例化
@classmethod
def ince(cls):
return cls(hwk_settings.HOST, hwk_settings.PORT)
# 4.为对象定制方法,save和get_obj_by_id,save能自动将对象序列化到文件中,文件路径为配置文件中DB_PATH,文件名为id号,保存之前验证对象是否已经存在,若存在则抛出异常,;get_obj_by_id方法用来从文件中反序列化出对象
def save(self):
if self.exist():
raise PermissionError('对象已存在')
else:
path = os.path.join(hwk_settings.PATH, self.id)
pickle.dump(self, open(path, 'wb'))
def exist(self):
state = False
if not os.path.exists(hwk_settings.PATH):
os.mkdir(hwk_settings.PATH)
files_name = os.listdir(hwk_settings.PATH)
for file_name in files_name:
file_path = r'%s%s%s' % (hwk_settings.PATH, os.sep, file_name)
obj = pickle.load(open(file_path, 'rb'))
if (obj.host == self.host) and (obj.port == self.port):
state = True
return state
def get_obj_by_id(self):
path = os.path.join(hwk_settings.PATH, self.id)
with open(path, 'rb') as fr:
obj = pickle.load(fr)
return obj
# obj1 = MySql('tank', 'handsome')
# obj1.save()
# obj1.get_obj_by_id()
# print(obj1.__dict__)
obj2 = MySql.ince()
obj2.save()
obj2.get_obj_by_id()
print(obj2.__dict__)
# 2、定义一个类:圆形,该类有半径,周长,面积等属性,将半径隐藏起来,将周长与面积开放
import cmath
class Circle:
def __init__(self, radius):
self.__radius = radius
@property
def area(self):
return cmath.pi * self.__radius ** 2
@property
def perimeter(self):
return 2 * cmath.pi * self.__radius
c = Circle(5)
print(c.area)
print(c.perimeter)
# 3、使用abc模块定义一个phone抽象类 并编写一个具体的实现类
import abc
class Phone(metaclass=abc.ABCMeta):
@abc.abstractmethod
def call(self):
pass
class Iphone(Phone):
def call(self):
print('使用ios系统及A11处理器打电话')
i = Iphone()
i.call()
'''
4、着手编写选课系统作业:http://www.cnblogs.com/linhaifeng/articles/6182264.html#_label15
'''