Home > Enterprise >  Python: Unable to call function within a seperate function? (undefined name 'getItemClassiness&
Python: Unable to call function within a seperate function? (undefined name 'getItemClassiness&

Time:06-01

For some reason the getClassiness Function does not work as it is not able to call the helper function getItemClassiness. Is there any reason this might be? Thanks!

class Classy(object):
    def __init__(self):
        self.items = []
    
    def addItem(self, item):
        self.items.append(item)
        
    def getItemClassiness(item):
        if item == "tophat":
            return 2
        if item == "bowtie":
            return 4
        if item == "monocle":
            return 5
        return 0
    
    
    def getClassiness(self):
        total = 0
        for item in self.items:
            x = getItemClassiness(item)
            total  = x
        return total

# Test cases

me = Classy()

# Should be 0
print(me.getClassiness())


# Should be 2
me.addItem("tophat")
print(me.getClassiness())

me.addItem("bowtie")
me.addItem("jacket")
me.addItem("monocle")
print(me.getClassiness())
# Should be 11


me.addItem("bowtie\n")
print(me.getClassiness())
# Should be 15

You can use this class to represent how classy someone or something is. "Classy" is interchangable with "fancy". If you add fancy-looking items, you will increase your "classiness". Create a function in "Classy" that takes a string as input and adds it to the "items" list. Another method should calculate the "classiness" value based on the items. The following items have classiness points associated with them: "tophat" = 2 "bowtie" = 4 "monocle" = 5 Everything else has 0 points. Use the test cases below to guide you!

CodePudding user response:

You should declare getItemClassiness as a static method because it doesn't require a specific instance. Then you can call the function as you would an instance method.

    @staticmethod
    def getItemClassiness(item):
        ...
    
    
    def getClassiness(self):
        ...
        for item in self.items:
            x = self.getItemClassiness(item)

But still it won't give you 15 for the last test case, because "bowtie" != "bowtie\n". If you intend to ignore white space at the start or the end of the string, use str.strip().

CodePudding user response:

In line 21 call for a class method is made without using the self keyword.

 x = self.getItemClassiness(item)

Similarly on line 8 in self keyword is required with as parameter for function definition of getItemClassiness

def getItemClassiness(self, item):
  • Related