1.作业
class People:
def __init__(self,name,age,sex):
self.name=name
self.age=age
self.sex=sex
def add_course(self,course_obj):
self.course_list.append(course_obj)
def tell_all_course_info(self):
for course_obj in self.course_list:
course_obj.tell_course_info()
class Teacher(People):
def __init__(self,name,age,sex):
super().__init__(name,age,sex)
self.course_list=[]
class Student(People):
def __init__(self,name,age,sex):
super().__init__(name,age,sex)
self.course_list=[]
class Course:
def __init__(self,course_name,course_period,course_price):
self.course_name=course_name
self.course_period=course_period
self.course_price=course_price
def tell_course_info(self):
print (f"""
=====课程 信息=====
"课程名字":{self.course_name},
"课程周期":{self.course_period},
"课程价格":{self.course_price},
""")
tea1=Teacher('tank',19,'male')
python_obj=Course('python',2,20)
linux_obj=Course('linux',3,20)
tea1.add_course(python_obj)
tea1.add_course(linux_obj)
tea1.tell_all_course_info()
print ('*'*100)
python_obj.tell_course_info()
print ('+'*100)
linux_obj.tell_course_info()
2.定义MySQL类
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 hashlib
import time
import settings
import pickle
class MySQL:
def __init__(self, host, port):
self.host = host
self.port = port
self.id = create_id()
def create_id(self):
m = hashlib.md5(str(time.time()).encode('utf8'))
return m.hexdigest()
def save(self):
if not self.is_exists:
raise PermissionError('对象已存在')
file_path = r'%s%s%s'%(settings.DB_PATH, os.sep, self.id)
pickle.dump(self, open(file_path,'wb'))
@property
def is_exists(self):
tag = True
files = os.listdir(settings.DB_PATH)
for file in files:
file_abspath = r'%s%s%s' % (settings.DB_PATH, os.sep, file)
obj = pickle.load(open(file_abspath, 'rb'))
if self.host == obj.host and self.port == obj.port:
tag = False
break
return tag
@staticmethod
def get_obj_by_id(id):
file_abspath = r'%s%s%s' % (settings.DB_PATH, os.sep, id)
return pickle.load(open(file_abspath, 'rb'))
@classmethod
def from_conf(cls):
print(cls)
return cls(settings.HOST, settings.PORT)
m1 = MySQL.from_conf()
m1.save()
m1 = MySQL('20.02.02.02', 6666)
m1.save()
obj = MySQL.get_obj_by_id('7e6c5ec0-7e9f-11e7-9acc-408d5c2f84ca')
print(obj.host)
3.定义一个类:圆形,该类有半径,周长,面积等属性,将半径隐藏起来,将周长与面积开放
import math
class Circle:
def __init__(self, radius):
self.__radius = radius
def area(self):
return math.pi * self.radius**2
def perimeter(self):
return 2 * math.pi * radius
4.使用abc模块定义一个phone抽象类 并编写一个具体的实现类
import abc
class Phone(metaclass=abc.ABCMeta):
@abc.abstractmethod
def call(self):
pass
@abc.abstractmethod
def listen(self):
pass
@abc.abstractmethod
def msg(self):
pass
class CellPhone():
def call(self):
pass
def listen(self):
pass
def msg(self):
pass
def color(self):
pass
xiaomi = CellPhone()