TypeError: name 'peek' is not defined

Hello again!

So, I’ve coded my parser and tested it to make sure everything is working. Now, I’m trying to implement it using object-oriented programming and see if I like this way more, as opposed to solely using methods. Admittedly, I think there’s considerable overlap between the two.

I came across an error with my skip() method. Here’s my code:

class Parse(object):

    def __init__(self, word_list):
        self.word_list = word_list

    def peek(self):
        return self.word_list[0]

    def match(self, expecting):
        word = self.word_list.pop(0)

        if word[0] == expecting:
            return word
            return None

    def skip(self):
        while self.peek() == 'stop':
            match(self.word_list, 'stop')

As I was creating a nosetest to test all of my methods, I encountered an issue with my skip() method. A TypeError was being thrown, saying that the name ‘peek’ was not defined. The solution was simple: I needed to add self right before I implemented peek() in the skip() method. I noticed we did this in Exercise 43 as well with our scene_map (I think?), where we were first introduced to object-oriented programming.

So, why the need to use self in this instance? Is it because we’re calling it on an instance of the Parse class?

Easy, you have to use self.peek to talk about peek. Same for skip and match.

Right, I figured. Thanks!