0

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?

2
  • 1
    After you fix this problem (by following Blender's answer), you're going to have another problem: the Parser.hasMoreCommands method is trying to access a variable named c, but there's no local or global with that name. The fact that jacklex.py has a global with the same name won't help you. If you want Parser to see it, you need to pass it over. For example, def hasMoreCommands(self, c):, then while parser.hasMoreCommands(c): Commented Feb 13, 2013 at 1:21
  • if I want to continually read c I would want it inside the loop, but when I put c = f.read(1) inside my loop I get an error saying "name 'c' is not defined' and it's referring to the line while parser.hasMoreCommands(c) How would I then get past this error? Commented Feb 13, 2013 at 1:42

1 Answer 1

3

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():
    ...
Sign up to request clarification or add additional context in comments.

2 Comments

+1. Except saying it refers to the "class method" is misleading. It's not a classmethod, it's a normal (unbound) method.
I'm sure you'll get used to the 2.x terminology just in time to move to 3.x, where things are different. Just like I'm finally learning to say "classic class" instead of "old-style class". :)

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.