【发布时间】:2022-12-02 05:30:18
【问题描述】:
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!
【问题讨论】:
-
Sorry, I misread. There are two problems here:
getItemClassinessshould be a@staticmethod, and it needs to be explicitly looked up likeClassy.getItemClassiness- yes, even within otherClassymethods. Python does not have "implicitthis" - hence all the explicitselfparameters - so other methods of the class are not in the local scope. -
See for example stackoverflow.com/questions/136097 and stackoverflow.com/questions/68645 .