How to return a list from a class

Question:

How would I get to return a list from the class, right now its just returning the location

class ListNode:
    def __init__(self, val=[]):
        self.val = val

    def __iter__(self):
        return iter(self.val)


def file_reader(file_path):
    list_of_num = [] 
    with open(file_path, "rt") as fout:
        reader = csv.reader(fout, delimiter=",")
        for line in reader:
            list_of_num.append(line)
    return list_of_num

def list_instances():
    lists = file_reader(list_path)
    final_list = ListNode(lists)
    return final_list 


if __name__=="__main__":
    file_reader(list_path)
    print(list_instances())
    

Any ideas, I think it has something to do with the iter object

Asked By: stang-Spitfire1975

||

Answers:

The problem is the ListNode class, which doesn’t do anything other than wrap a regular list (it also has a potential bug related to the mutable default arg in the constructor that might bite you later), and it doesn’t wrap the __str__ method that provides pretty-printing.

The easiest way to solve the problem is to just not use ListNode:

def list_instances():
    return file_reader(list_path)

Now your print call will receive a list instead of a ListNode and it will print the contents of the list.

You can also write file_reader() more simply as:

def file_reader(file_path):
    with open(file_path, "rt") as fout:
        return list(csv.reader(fout))

since csv.reader is an iterable, and passing an iterable to list() will give you a list of its contents; you don’t need to write the for loop yourself and individually append each element.

Answered By: Samwise
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.