Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private helper functions in Python classes

Tags:

python

oop

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?

like image 447
jorgenfar Avatar asked Jul 10 '14 08:07

jorgenfar


People also ask

What are helper functions in Python?

What is a helper function in Python? A helper function is a function that performs part of the computation of another function following the DRY (Don't repeat yourself) concept.

What are helper classes in Python?

In object-oriented programming, a helper class is used to assist in providing some functionality, which isn't the main goal of the application or class in which it is used.

Are helper methods private or public?

Helper methods are often declared as public static so they can be invoked with the class name like Classname. method(). For example, below I have created a HelperMethods class which consists of helper methods that I can use across multiple classes.


1 Answers

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

like image 94
myildirim Avatar answered Sep 20 '22 03:09

myildirim