1

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.

1
  • Please don't name your variables list, it's already the name of the built-in list type. Commented Oct 18, 2012 at 22:20

3 Answers 3

3

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)
answered Oct 18, 2012 at 22:16
Sign up to request clarification or add additional context in comments.

2 Comments

No problem! If this did solve your problem, could you mark my answer accepted? Thanks!
Done. :) It wouldn't let me accept your answer before a few minutes had passed.
1

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.

answered Oct 18, 2012 at 22:16

Comments

1

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.

answered Oct 18, 2012 at 22:16

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.