"""
类似java对象序列化到文件
Python完美实现
"""
import pickle
# 写对象到文件
class Person(object):
def __init__(self, name, age, address):
self.name = name
self.age = age
self.address = address
def eat(self):
print('吃')
def drink(self):
print('喝')
def sleep(self):
print('睡')
person = Person('zhangsan', 18, 'sz')
print(person, person.name, person.age, person.address) # <__main__.Person object at 0x0000000002680198> zhangsan 18 sz
file = open(__file__ + '.bin', 'wb')
pickle.dump(person, file)
file.close()
# 读取对象
file = open(__file__ + '.bin', 'rb')
obj = pickle.load(file)
print(obj, type(obj), obj.name, obj.age, obj.address) # <__main__.Person object at 0x000000001223E7F0> zhangsan 18 sz
obj.eat() # 吃
obj.drink() # 喝
obj.sleep() # 睡
file.close()