Chris Searcy
Chris Searcy

Reputation: 94

Python: Importing class from another file and implementing function

I'm trying to import a class from another file and then implement the member function in my main function. I'm really just trying to understand the syntax of Python, as I am still really new to the language. My program is simple, and isn't really meant to do much. I'm more or less just trying to get a grasp on how Python goes about this. My class file is called Parser.py and here's is the code:

class Parser:
def hasMoreCommands(self):

    if not c:
        return false
    else:
        return true

and my main function is in a file called jacklex.py The main function only opens an input file and copies the text to an output file. Here's the code:

import Parser
from Parser import *

f = open('/Python27/JackLex.txt' , 'r+')
fout = open('/Python27/output.txt' , 'w')

while Parser.hasMoreCommands:
    c = f.read(1)
    fout.write(c)
print "All Done" 
f.close()
fout.close()

My issue is that my program runs, but it seems to be getting stuck in an infinite loop. There's never any text printed to the ouput file, and "All Done" is never printed in the Python Shell. Am I missing something essential that's causing my program not to work properly?

Upvotes: 0

Views: 4866

Answers (1)

Blender
Blender

Reputation: 298196

Parser.hasMoreCommands refers to the (unbound) method, not the output. It'll always evaluate to True.

You need to create an instance of your parser and then call the method:

parser = Parser()

while parser.hasMoreCommands():
    ...

Upvotes: 3

Related Questions