0

This is an exercise that I wanted to try because I thought it was interesting. The exercise is unnecessarily complex for what it is doing, but it is trying to act as practice for understanding class, function and variable behavior in more complex python programs.

import os

class grabFile:
    fileObject = None
    def __init__(self, filename):
        self.fileObject = open(filename, "r")

    def getFile():
        return self.fileObject

class counter:
    fileC = None
    lineCount = 0
    def __init__(self, fileObject):
        self.fileC = fileObject

    def lineCounter(self):
        while True:
            self.fileC.readline()
            print(x)
        return lineCount


def Main():
    fileGrabber = grabFile("test.txt")
    fileObj = fileGrabber.getFile

    countObj = counter(fileObj)
    lineCount = countObj.lineCounter()
    print(lineCount)

Main()

However, when I run this, I get the following error:

Traceback (most recent call last):
  File "/home/may/Desktop/Tree/Programming/MiscProjects/TextAnalyzer.py", line 32, in <module>
Main()
  File "/home/may/Desktop/Tree/Programming/MiscProjects/TextAnalyzer.py", line 29, in Main
lineCount = countObj.lineCounter()
  File "/home/may/Desktop/Tree/Programming/MiscProjects/TextAnalyzer.py", line 19, in lineCounter
self.fileC.readline()
AttributeError: 'function' object has no attribute 'readline'
[Finished in 0.2s with exit code 1]

Can anyone help me understand this program fully? And also, although this is not the correct place to ask, offer any critique on styling or formatting of the program? Especially one the use of "self".

Thank you!

1 Answer 1

3

I think you meant to call the method:

fileObj = fileGrabber.getFile()

And you need to change to instance method:

def getFile(self):
    return self.fileObject

And your line counter method needs some work:

def lineCounter(self):
    self.lineCount = len(self.fileC.readlines())
    return self.lineCount
Sign up to request clarification or add additional context in comments.

6 Comments

that's not instantiation. it's a simple function call.
I also believed that was the correct way to go about it, but when I do that, I get an error about how getFile has 0 positional arguments, but I gave it 1?
@KarolyHorvath My bad, I'm falling asleep I guess.
@Utagai Answer updated. Your method took no instance object as an argument.
Also your line counter method is an infinite loop with no purpose try the code here.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.