理解python中的变量范围:练习程序

时间:2015-03-16 22:58:31

标签: python

这是一个我想尝试的练习,因为我觉得它很有趣。这个练习对于它正在做的事情来说是不必要的复杂,但是它试图在更复杂的python程序中理解类,函数和变量行为。

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()

但是,当我运行它时,我收到以下错误:

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]

任何人都可以帮助我完全理解这个程序吗?而且,虽然这不是正确的问题,但对程序的样式或格式提出任何批评?特别是使用“自我”。

谢谢!

1 个答案:

答案 0 :(得分:3)

我认为您打算调用该方法:

fileObj = fileGrabber.getFile()

您需要更改为实例方法:

def getFile(self):
    return self.fileObject

你的行计数器方法需要做一些工作:

def lineCounter(self):
    self.lineCount = len(self.fileC.readlines())
    return self.lineCount