from pickle import dumps, loads
class Student:
def __init__(self, username, sex, age):
'''username为字符串,sex为'Female'或'Male',age为正整数'''
self.username = username
self.sex = sex
self.age = age
def __str__(self):
return str(self.__dict__)
__repr__ = __str__
def __getstate__(self):
dic = self.__dict__.copy()
if dic["sex"] == "Female":
del dic["age"]
return dic
def __setstate__(self, state):
self.__dict__.update(state)
if (state["sex"] == "Female"):
self.__dict__["age"] = 18
def main(stu):
stu_dummped = dumps(stu)
return (stu_dummped, loads(stu_dummped))
# s1 = Student("abc", "Male", 20)
# s2 = Student("def", "Female", 20)
# print(main(s2))
|