views:

115

answers:

1

Here is some snippet code. I have tested the methods listed and they work correctly, yet when I run and test this method (countLOC) it only seems to initialize the first variable that has an instance method call (i = self.countBlankLines()). Anyone know the obvious reason I'm obviously missing?

def countLOC(self):  
    i = self.countBlankLines()  
    j = self.countDocStringLines()  
    k = self.countLines()  
    p = self.countCommentLines()  
    return k-i-j-p

This returns -3 because countBlankLines() returns 3 (correctly). however, it should return 37 as countDocStringLines() = 6 and countCommentLines() = 4 while countLines() = 50. Thanks.

+5  A: 

If local variables were not initialized (impossible given your code!) they wouldn't be 0 -- rather, you'd get a NameError exception when you try to use them. It's 100% certain that those other method calls (except the first one) are returning 0 (or numbers totaling to 0 in the expression).

Hard to guess, not being shown their code, but from your comment my crystal ball tells me you have an iterator as an instance variable: the first method to iterate on it exhausts it, the other methods therefore find it empty.

Alex Martelli
Nice guess! ...
sth
Yes, your guess was correct. I did not realize the iteration exhausted it since i did have it as instance. Thanks a lot. (very new to python) :)
Bill Atkinson
This sounds about right.. If the functions are iterating over a file handle, each function would need to do `self.fh.seek(0)`. Perhaps more cleanly (but less efficiently) you could do something like `self.lines = open('myfile').readlines()` in the classes `__init__` method
dbr