kjames kjames - 4 months ago 13
Python Question

Python -- Issues with method as parameter?

I am making a "Choose Your Adventure" game in Python. As you will see in the code below, I have a method temporarily called unnamedMethod that has three parameters: a method, m; a string, ans1; and another string, ans2.

This method is supposed to handle the user's input derived from m and check to see if it equals one of two words. If it doesn't equal either word, then it should print a simple error message ("Please submit a valid response.") and call the method m again. However, I get the error message "str is not callable" with my current code.

Here is my project so far:

class player:

def __init__(self, n):
self.name = n
self.inventory = []
self.health = 10.0

def getName(self):
return self.name

def printName(self):
print("Your name is: " + self.name)

def printInventory(self):
print(self.inventory)


class game:

def __init__(self):
print("Welcome to Choose Your Adventure.")
name = input("Please enter your name to begin: ")
p = player(name)

def intro(self):
print("\n.....\n")
ans = input("You awaken in a field skirted by a dense pine forest.\n" +
"A rickety barn and its adjoining house lie a few hundred\n" +
"feet ahead of you. Do you enter the forest or explore the\n" +
"property? Type 'property' or 'forest': ")
return ans

def property(self):
print("\n.....\n")
print("You walked towards the property")

def forest(self):
print("\n.....\n")
print("You walked into the forest")

###

def unnamedMethod(self, m, ans1, ans2):
ans = m() #where the error message occurs
while ans.lower() != ans1 and ans.lower() != ans2:
print("Please submit a valid response.")
print("\n.....\n\n")
ans = m()
if ans.lower() == ans1:
return ans1
else:
return ans2


class run:

def __init__(self):
g = game()
print(g.unnamedMethod(g.intro(), "property", "forest"))


r = run()


If my code is running properly, it will loop through intro() until the user inputs "property" or "forest," and then it will print the corresponding word. I would greatly appreciate it if someone could help me find the issue with my code.

Answer

g.intro() returns a string, so all you need do is assign the returned value of the method which is passed as m to ans:

ans = m

If you want m to be treated as callable, then consider passing g.intro instead:

g.unnamedMethod(g.intro, "property", "forest")
...
ans = m()