4.16作业

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 os
import time
import pickle
import hashlib
import settings



class Mysql:
    def __init__(self,host,port):
        self.id = self.creta_id()
        self.host =host
        self.port = port

    @staticmethod
    def creta_id():
        m = hashlib.md5()
        m.update(str(time.clock()).encode('utf-8'))
        return m.hexdigest()

    def save(self):
        path = os.path.join(settings.DB_path,'%s.pickle' %self.id)
        if os.path.isfile(path):
            raise IOError('对象已存在')
        else:
            with open(path,'wb') as f:
                pickle.dump(self,f)

    @staticmethod
    def get_obj_by_id(id):
        path = os.path.join(settings.DB_path, '%s.pickle' %id)
        if os.path.isfile(path):
            with open(path,'rb') as f:
                return pickle.load(f)
        else:
            raise IOError('对象不存在')


    def tell(self):
        print('id:%s,host:%s,port:%s' %(self.id,self.host,self.port))

    @classmethod
    def from_conf(cls):
        return cls(settings.HOST,settings.PORT)

# mysql = Mysql('127.0.0.1','3309')
# mysql = Mysql.from_conf()
# mysql.save()
# mysql.tell()
# f = Mysql.get_obj_by_id('30565a8911a6bb487e3745c0ea3c8224')
# f.tell()
作业1

2、定义一个类:圆形,该类有半径,周长,面积等属性,将半径隐藏起来,将周长与面积开放
参考答案(http://www.cnblogs.com/linhaifeng/articles/7340801.html#_label4)

import math
class Round:
    def __init__(self,radius):
        self.__radius = radius
    @property
    def radius(self):
        return self.__radius

    @radius.setter
    def radius(self,x):
        self.__radius = x

    def perimeter(self):
        round_perimeter = math.pi *(self.__radius * 2)
        return round_perimeter

    def area(self):
        round_area = math.pi * (self.__radius * self.__radius)
        return round_area

round1 = Round(3)
print(round1.perimeter())
print(round1.area())
round1.radius = 4
print(round1.perimeter())
print(round1.area())
作业2

 

posted @ 2018-04-16 16:36  木夂口  阅读(164)  评论(0编辑  收藏  举报
levels of contents