简体   繁体   中英

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.

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)

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM