Private helper functions in Python classes are giving "global name <name of method> is not defined"

oop, python

Solution

In your question you are missing `self`;

def _getItemName(self, item):
    str = ""
    for c in item:
        if c!= '(':
            str += c
        else:
            break
    return str

def getCertainItemsByName(self, key, name):
    foundItems = []
    for item in self.itemMap[key]:
        if self._getItemName(item) == name:
            foundItems.append(item)

You should look at `static method`, `class method` and `instance method` in Python.

Static methods are a special case of methods. Sometimes, you'll write code that belongs to a class, but that doesn't use the object itself at all. For example:

class Pizza(object):
     @staticmethod
     def mix_ingredients(x, y):
         return x + y

     def cook(self):
         return self.mix_ingredients(self.cheese, self.vegetables)

For more, you can visit here

Problem

I am creating a class which holds a dict, and has some methods to extract information based on the data in the dict. Each key points to a list of strings. Each string in the list is of the form `name(data).` I am very new to programming in Python and have mainly used Java previously. I have created a couple of private helper functions that are to be used for in my public methods. Here is an example to illustrate what I'm trying to do: ``` def _getItemName(item): str = "" for c in item: if c!= '(': str += c else: break return str ``` This method is then used in several public methods, like in this example: ``` def getCertainItemsByName(self, key, name): foundItems = [] for item in self.itemMap[key]: if _getItemName(item) == name: foundItems.append(item) return foundItems ``` This is giving me an error equivalent to "global name "_getItemName" is not defined. I realize I could just declare the method outside of the class, but the method is class-specific so that's not something I want to do. What is the best to do this?

Original source