猿问

如何将内容传递到python中的类的实例中

我有一个 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() 调用的实例,这是为了学习目的。


临摹微笑
浏览 216回答 3
3回答

千巷猫影

class Book():    def __init__(self,poem="empty"):        self.poem = poem    def __str__(self):        return self.poemdef 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=stringb1 = 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?
随时随地看视频慕课网APP

相关分类

Python
我要回答