今日作业
'''
0、课堂代码理解,并敲两遍以上 (技术的牛逼是靠量的积累)
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方法用来从文件中反序列化出对象
2、定义一个类:圆形,该类有半径,周长,面积等属性,将半径隐藏起来,将周长与面积开放
参考答案(http://www.cnblogs.com/linhaifeng/articles/7340801.html#_label4)
3、使用abc模块定义一个phone抽象类 并编写一个具体的实现类
4、着手编写选课系统作业:http://www.cnblogs.com/linhaifeng/articles/6182264.html#_label15
'''
from config import setting
import os
import pickle
from datetime import datetime
import hashlib
'''
setting.py
import os
base_path = os.path.dirname(os.path.dirname(__file__))
db_path = os.path.join(base_path, '1011work')
host = '001'
port = '002'
'''
def save(obj):
classify = obj.__class__.__name__.lower()
class_path = os.path.join(setting.db_path, classify)
if not os.path.exists(class_path):
os.mkdir(class_path)
file_list = os.listdir(class_path)
for file in file_list:
file_abspath = os.path.join(class_path, file)
obj_load = pickle.load(open(file_abspath, 'rb'))
if obj.host == obj_load.host and obj.port == obj_load.port:
return '已存在'
id = obj.id
file_path = os.path.join(class_path, id)
with open(file_path, 'wb')as fw:
pickle.dump(obj, fw)
def select(classify, id):
file_path = os.path.join(setting.db_path, classify, id)
if not os.path.exists(file_path):
return False
with open(file_path, 'rb')as fr:
obj = pickle.load(fr)
return obj
class BaseClass(object):
def save(self):
save(self)
@classmethod
def get_obj_by_id(cls, id):
obj = select(cls.__name__.lower(), id)
return obj
class Mysql(BaseClass):
def __init__(self, host, port):
self.host = host
self.port = port
self.create_id()
self.save()
def create_id(self):
# self.id = str(hash(str(time.time())))
res = datetime.today().strftime('%Y-%m-%d %X')
m = hashlib.md5()
m.update(bytes(res, encoding='utf-8'))
self.id = str(m.hexdigest())
self.save()
mysql = Mysql('001','002')
tank = (mysql.__class__).get_obj_by_id(mysql.id)
if not tank:
print(tank)
else:
print('tank', tank.__dict__)
import math
class Circle:
def __init__(self, radius):
self.__radius = radius
self.perimeter = radius*2*math.pi
self.area = radius*radius*math.pi
------------------------------------------
import math
class Circle:
def __init__(self,radius): #圆的半径radius
self.radius=radius
@property
def area(self):
return math.pi * self.radius**2 #计算面积
@property
def perimeter(self):
return 2*math.pi*self.radius #计算周长
c=Circle(10)
print(c.radius)
print(c.area) #可以向访问数据属性一样去访问area,会触发一个函数的执行,动态计算出一个值
print(c.perimeter) #同上
import abc
class Phone(metaclass=abc.ABCMeta):
@abc.abstractmethod
def call(self):
print('报警了')
class Iphone(Phone):
def call(self):
print('110')
iphone11 = Iphone()
iphone11.call()