DirtyDaver DirtyDaver - 1 month ago 10
Python Question

using a tail and a buffer to get last K lines in a file

I was given this buffer and told to make a reverse input that get the last K lines in a file. From what I've been trying to do, every time I tried to run the code it says that used is not an attribute of Input. Can someone please tell me why this keeps happening? Thank you in advance.

class Input:
def __init___( self, file ):
self.file = file # must open( <filename>, "rb" )
self.length = 0
self.used = 0
self.buffer = ""
def read( self ):
if self.used < self.length: # if something in buffer
c = self.buffer[self.used]
self.used += 1
return c
else:
self.buffer = self.file.read( 20 ) # or 2048
self.length = len( self.buffer )
if self.length == 0:
return -1
else:
c = self.buffer[0]
self.used = 1

`

Answer

I'm going to go out on a limb here and try guessing that the problem is that you are using the wrong name for the __init__ magic method (as noticed by Hai Vu). Notice that there are three trailing underscores in your code instead of two.

Since the __init__ method is the one called during the construction of the object to set its various attributes, the used attribute never gets set because the __init__ function never gets run.

Afterwards, used is the first attribute accessed in Input.read, which makes Python complain about it being missing.

If I'm right, remove the underscore and it will fix the problem (though there may be others).