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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With