保存学员信息

保存学员信息

需求:将修改后的学员信息数据保存到存储数据文件

步骤:

思考:

  1. 文件写入的数据是学员对象的内存地址吗?不是,是字典。
  2. 文件内数据要求的数据类型是什么?是字符串

拓展知识__dict__ : 是python中类对象和实例对象都拥有的属性,其作用是收集类对象和实例对象的属性和方法以及对应的值,从而返回一个字典。

class A(object):
	a = 0

	def __init__(self):
		self.b = 1

aa = A()
# 返回类内部所有属性和方法对应的字典
print(A.__dict__)	# {'__module__': '__main__', 'a': 0, '__init__': <function A.__init__ at 0x000001D44BC09E40>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
# 返回实例属性和值组成的字典
print(aa.__dict__) # {'b': 1}

保存学员信息代码如下:

# 2.7 保存学员信息
    def save_student(self):
        # 1. 打开文件
        f = open('student.data', 'w')
        # 2. 文件写入数据
        # 2.1 [学员对象]转换成[字典]
        new_list = [i.__dict__ for i in self.student_list]
        # 2.2 文件写入字符串数据
        f.write(str(new_list))
        # 3. 关闭文件
        f.close()