Gregory
Gregory

Reputation: 4279

Python3: How to get value from other file with function within class?

I want to create a class for storing attributes of the many data files that my script has to process. The attributes are values that are found in the datafiles, or values that are calculated from other values that are found in the data files.

Unfortunately, I'm not understanding the output of the code that I've written to accomplish that goal. What I think this should do is: print the name of the file being processed and a value seqlength from that file. The actual output is given below the code.

class SrcFile:

   def __init__(self, which):
      self.name = which       

   def seqlength(self):
      with open(self.name) as file:
         linecounter = 0
         for line in file:
            linecounter += 1
            if linecounter == 3:
            self.seqlength = int(line.split()[0])
            break

for f in files:
    file = SrcFile(f)
    print(file.name, file.seqlength)

This prints file.name as expected, but for file.seqlength it returns a value that I don't understand.

../Testdata/12_indels.ss <bound method SrcFile.seqlength of <__main__.SrcFile object at 0x10066cad0>>

It's clear to me that I'm not understanding something fundamental about classes and functions. Is it clear to you what I'm missing here?

Upvotes: 0

Views: 216

Answers (2)

robert
robert

Reputation: 34398

.seqlength is a method and needs (), but you are also not returning anything from it. Try this instead:

 def seqlength(self):
     with open(self.name) as file:
         linecounter = 0
         for line in file:
             linecounter += 1
             if linecounter == 3:
                 return int(line.split()[0])

And then calling it:

for f in files:
    file = SrcFile(f)
    print(file.name, file.seqlength())

Upvotes: 2

Jakob Bowyer
Jakob Bowyer

Reputation: 34688

Thats because .seqlength is a method.

Try doing

print(filename, file.seqlength())

Upvotes: 0

Related Questions