# 一:定义一个People类,每个人的对象都有名字\年龄\性别三个属性
# 分别完成对这个三个属性的:隐藏\开放接口\property伪装操作
# ps:在开放的接口里严格控制赋值操作的数据类型问题
class People:
def __init__(self, name, age, gender):
self.__name = name
self.__age = age
self.__gender = gender
@property
def name(self):
print('查看')
return self.__name
@name.setter
def name(self, name):
print('修改')
self.__name = name
@name.deleter
def name(self):
del self.__name
@property
def age(self):
print('查看')
return self.__age
@age.setter
def age(self, age):
print('修改')
if type(age) is not int:
print('数字必须是整型!')
return
self.__age = age
@age.deleter
def name(self):
del self.__age
p1 = People('Alex', 18, 'female')
print(p1.age)
p1.name = '19'
print(p1.age)
方法一
二:定义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 uuid
import settings
class MySQL:
def __init__(self, host, post):
self.__id = self.Create_id()
self.post = post
self.host = host
@property
def name(self):
print('id:%s host:%s post:%s' % (self.__id, self.host, self.post))
def Create_id(self):
return uuid.uuid4()
@classmethod
def from_conf(cls):
return cls(settings.host, settings.post)
M1 = MySQL(123,456)
print(M1.name)
方法二
import uuid
import settings
class MySQL:
def __init__(self, host, post):
self.__id = self.Create_id()
self.post = post
self.host = host
@property
def name(self):
print('id:%s host:%s post:%s' % (self.__id, self.host, self.post))
def Create_id(self):
return uuid.uuid4()
@classmethod
def from_conf(cls):
return cls(settings.host, settings.post)
M1 = MySQL.from_conf()
print(M1.name)
import uuid
import settings
import os
import pickle
class MySQL:
def __init__(self, host, post):
self.__id = self.Create_id()
self.post = post
self.host = host
@property
def name(self):
print('id:%s host:%s post:%s' % (self.__id, self.host, self.post))
def Create_id(self):
return uuid.uuid4()
@classmethod
def from_conf(cls):
return cls(settings.host, settings.post)
def save(self):
base_path = os.path.dirname(__file__)
path = os.path.join(base_path, '%s.txt' % self.__id)
if os.path.exists(path):
print('用户已经存在!')
else:
pickle.dump(self, open(path, 'wb'))
M1 = MySQL.from_conf()
print(M1.name)
M1.save()