4.16作業
阿新 • • 發佈:2018-04-16
eth @property ID lse spl nbsp open display 參考答案
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(作業1‘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) @staticmethoddef 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()
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
4.16作業