我有一个 Book 类,这基本上只返回现在的内容,但是我有一个需要读取的外部文件,然后将内容传递到该实例中,例如我开始将 book 实例声明为 b1class Book(): def __init__(self,poem="empty"): self.poem = poem def __str__(self): return self.poemdef 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 instanceb1 = Book() # book has a default value so it wont make any errorreading(b1, "file.txt")print("File contains:",b1) # prints empty, because reading function has not passed any data i think问题是现在它总是只打印“空”,我如何将从文件中读取的数据传递给在 reading() 调用的实例,这是为了学习目的。
3 回答

千巷猫影
TA贡献1829条经验 获得超7个赞
class Book():
def __init__(self,poem="empty"):
self.poem = poem
def __str__(self):
return self.poem
def reading(self, 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)
self.poem=string
b1 = Book()
reading(b1, "file.txt")
print("File contains:",b1)
输出
File contains: I really love christmas Keep the change ya filthy animal Pizza is my fav food Did someone say peanut butter?
添加回答
举报
0/150
提交
取消