为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

临摹微笑 2021-09-28 20:43:57
我有一个 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?



查看完整回答
反对 回复 2021-09-28
  • 3 回答
  • 0 关注
  • 215 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号