How to pass the content into the instance of a class in python

Viewed 112

I have a class Book, and this basically only returns the content for now, but i have an external file that i need to read, and then pass the content into that instance, for instance i start declaring the book instance as 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

The problem is that now it does print always only "empty", how can i pass the data that i read from the file to the instance that is called at reading(), this is for learning purpose.

3 Answers
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)

Output

File contains: I really love christmas Keep the change ya filthy animal Pizza is my fav food Did someone say peanut butter?

For creating instances with some additional functionality for instance often used classmethods https://www.programiz.com/python-programming/methods/built-in/classmethod

Try this one:

class Book():
def __init__(self,poem="empty"):
    self.poem = poem

@classmethod
def load_book(cls, filename):
    list_of_content = []
    with open(filename, "r") as input_file:
        for line in input_file:
            list_of_content.append(line.split())
        flatten = [item for sublist in list_of_content for item in sublist]
        string = " ".join(flatten) 
        book_inst = cls(string)
        return book_inst

def __str__(self):
    return self.poem


book = Book.load_book("input.txt")
print(book)

reading should be a method of the class, but you could also just initialize Book when created:

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)

If you still want to create empty books and possibly read different files into the same Book, make read a method:

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)
Related