1.
'''
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 hashlib
import time
import os
import pickle
from conf import settings
class MySQL:
def __init__(self,host,port):
self.host = host
self.port = port
self.id = self.__create_id()
def __create_id(self):
id = hashlib.md5()
id.update(str(time.time()).encode('utf-8'))
return id.hexdigest()
def save(self):
file_path = os.path.join(settings.DB_PATH,F'{self.id}.pkl')
if os.path.exists(file_path):
raise('文件已存在')
with open(file_path,'wb')as fw:
pickle.dump(self,fw)
def get_obj_by_id(self,id):
file_path = os.path.join(settings.DB_PATH,f'{id}.pkl')
with open(file_path,'rb')as fr:
obj = pickle.load(fr)
return obj
def get_obj_1():
host = input('host:')
port = input('port:')
return MySQL(host,port)
def get_obj_2():
host = settings.host
port = settings.port
return MySQL(host,port)
x = get_obj_1
x.save()
2.
'''
2、定义一个类:圆形,该类有半径,周长,面积等属性,将半径隐藏起来,将周长与面积开放
参考答案(http://www.cnblogs.com/linhaifeng/articles/7340801.html#_label4)
'''
import math
class Circle:
def __init__(self, r):
self.__r = r
self.c = 2 * math.pi * r
self.s = math.pi * r ** 2
print(Circle(10).c)
3
'''
3、使用abc模块定义一个phone抽象类 并编写一个具体的实现类
'''
import abc
class Phone(metaclass=abc.ABCMeta):
def __init__(self, name, price):
self.name = name
self.price = price
@abc.abstractmethod
def input_num(self):
print('拨号:')
num = input()
class Xiaomi(Phone):
def input_num(self):
print('小米正在为您拨号:')
num = input()
print('拨号中....')
# 实例化
redmi = Xiaomi('redmi', 1299)
redmi.input_num()