我有一个 Book 类,这基本上只返回现在的内容,但是我有一个需要读取的外部文件,然后将内容传递到该实例中,例如我开始将 book 实例声明为 b1
class Book():
def __init__(self,poem="empty"):
self.poem = poem
def __str__(self):
return self.poem
def reading(instance, file_content):
list_of_content = []
with open(file_content, "r") as f:
for i in f:
list_of_content.append(i.split())
flatten = [item for sublist in list_of_content for item in sublist]
string = " ".join(flatten)
instance = Book(string)
return instance
b1 = Book() # book has a default value so it wont make any error
reading(b1, "file.txt")
print("File contains:",b1) # prints empty, because reading function has not passed any data i think
问题是现在它总是只打印“空”,我如何将从文件中读取的数据传递给在 reading() 调用的实例,这是为了学习目的。
千巷猫影
相关分类