Private helper functions in Python classes
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
Related videos on Youtube
jorgenfar
Updated on September 30, 2022Comments
-
jorgenfar over 1 year
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?
-
myildirim almost 10 yearsyou can use @staticmethod
-
jorgenfar almost 10 yearsI don't want to pass it self as an argument because it isn't an instance method. I guess I will make it static, but that isn't very appealing to me either because it is a method that is only to be used inside the class, so it seems unneccesarily clunky to need to prefix the class name when calling it inside the class definition.
-
-
jorgenfar almost 10 yearsThanks for the link! I was already aware of the possibility of making this static but I guess I was just looking for a more elegant way of doing this, similar to how it is done in Java.