gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:06:19 24 4
gpt4 key购买 nike

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

最佳答案

reading 应该是类的一个方法,但您也可以在创建时只初始化 Book:

class Book():

def __init__(self,filename):
list_of_content = []
with open(filename) as f:
for line in f:
list_of_content.append(line.split())
flatten = [item for sublist in list_of_content for item in sublist]
string = " ".join(flatten)
self.poem = string

def __str__(self):
return self.poem

b1 = Book('file.txt')
print("File contains:",b1)

如果您仍想创建空书并可能将不同的文件读入同一本Book,请将read 设为一个方法:

class Book():
def __init__(self,poem='<empty>'):
self.poem = poem

def read(self,filename):
list_of_content = []
with open(filename) as f:
for line in f:
list_of_content.append(line.split())
flatten = [item for sublist in list_of_content for item in sublist]
string = " ".join(flatten)
self.poem = string

def __str__(self):
return self.poem

b1 = Book()
print("File contains:",b1)
b1.read('file.txt')
print("File now contains:",b1)

关于python - 如何将内容传递给python中的类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53977203/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com