Robincognito
Robincognito

Reputation: 27

Python: issue with calling methods

I'm new to Python and I've written a class for managing a simple phonebook. (I've removed the methods that aren't relevant to this post).

class Phonebook:

    def __init__(self):
        self.book = {}

    def newEntry(self, name, number):
        self.book[name] = number

    def findNumber(self, name):
        return self.book[name]

    def nameList(self):
        list = self.book.keys()
        list.sort()
        for k in list:
            print k, self.book[k]

My question concerns the last method, nameList, which prints the phonebook entries (name and phone no.) in alphabetical order. Originally, I tried the following:

 def nameList(self):
        list = self.book.keys()
        list.sort()
        for k in list:
            print k, findNumber(k)

However, this threw up a "NameError" global name 'findNumber' is not defined" error. Would someone be able to explain why this didn't work?

Thanks in advance.

Upvotes: 1

Views: 111

Answers (3)

Serdalis
Serdalis

Reputation: 10489

you need to add self to findNumber()

so it would become:

def nameList(self):
        list = self.book.keys()
        list.sort()
        for k in list:
            print k, self.findNumber(k)

else it doesn't know where findNumber is coming from because it is only defined in your class, or, self.

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250921

findNumber(k) should be accessed as self.findNumber(k) when inside class.

or as Phonebook.findNumber(self,k).

because a variable or function declared under a class becomes a class's attribute.

Upvotes: 1

Sam Mussmann
Sam Mussmann

Reputation: 5983

This doesn't work because findNumber is not a globally defined function. It's a method on your object, so to call it, you would need to invoke self.findNumber(k).

So your example would look like:

 def nameList(self):
        list = self.book.keys()
        list.sort()
        for k in list:
            print k, self.findNumber(k)

Upvotes: 3

Related Questions