As I mentioned in the question comments, this is not a sensible thing to do, but here's how it can be done. To test this code I created a text file containing the integers 0 to 9, using the GNU coreutils command seq:
seq 0 9 >list.txt
And here's the Python code:
class AutoPrint(object):
def __init__(self, data):
self.data = data
def __getitem__(self, idx):
for row in self.data[idx]:
print(row)
def get_list(fname):
with open('list.txt') as f:
data = f.read().splitlines()
return AutoPrint(data)
get_list('list.txt')[2:5]
output
2
3
4
But please don't do crazy stuff like this in real code! My __getitem__ method returns None; a proper __getitem__ is supposed to return the selected item(s). And it shouldn't have crazy side-effects, like printing stuff. OTOH, I guess while you're developing the code it can be handy for it to print (or log) stuff so that you know that it's doing what you expect it to do.
lineslist from your function, then.withto automatically close the file when you're done with itget_list()[2:5]should print the selected lines, or do you merely wish it to return those lines (eg in a list or tuple)?