我有一个 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)
我是一名优秀的程序员,十分优秀!