我将对类 Task 的调用存储在 .dat 文件的数组中。我想阅读这个文件并重建类调用。
这是我现在正在使用的课程:
class Task:
def __init__(self, name, timespent):
self.name = name
self.timespent = timespent
def __repr__(self):
return repr('Task("%s",%s)'%(self.name, self.timespent))
这是从文件中读取的内容:
task_list = []
with open("task_list2.dat", "r") as file:
task_list = eval(file.readline())
这是对文件的写入:
with open("task_list2.dat", "w") as outFile:
print(repr(task_list), file = outFile)
这是文件的内容:
['Task("class",20)']
其中“class”是任务的名称。
我知道问题与 'Task("class",20)' 周围的单引号有关,但我不知道如何摆脱它们。我收到的错误消息大致如下:“str object has no attribute 'name'”
如何删除这些引号,以便下次阅读文件时可以重建类?