我有一个已定义的函数,其中包括一个计数器,它知道它被使用了多少次,并要求用户输入L、R或F。我希望它检查输入并将其添加到计数器中,并调用该名称的函数。用户选择L计数是在3调用函数L3
这是我到目前为止所得到的,但我得到了一个错误:
def getUserDirection():
getUserDirection.counter = 0
getUserDirection.counter += 1
direction = str(input("Which direction do you wish to go? (L/F/R) "))
direction = direction.upper()
if direction not in ("L", "F", "R"):
print("whats does {} mean? You were meant to type 'L', 'F' or 'R'! Try again..".format(direction))
direction = getUserDirection()
elif direction == "L":
print(direction()+counter())
elif direction == "F":
print(direction()+counter())
elif direction == "R":
print(direction()+counter())
return getUserDirection()我希望它调用的其他功能是:
def L1():
print("you go left and see...")
def F1():
print("You continue forward and see...")
def R1():
print("You go right and see...")其思想是循环遍历getUserDirection()并在每次传递时调用不同的函数。随着L1、L2、L3等功能的发展,将有大量的功能。每个人都有不同的故事和新的方向选择。
我做错了什么?
全码
#PLAYER DETAILS
first_name = input("What is your first name? ")
last_name = input("What is your last name? ")
while True:
middle = input("Do you have a middle name? (y/n) ")
if middle.upper() not in ("Y", "N"):
print("whats does {} mean? You were meant to type 'y' or 'n'! Try again.." .format(middle))
elif middle.upper() == "Y":
middle_name = input("What is it? ")
break
elif middle.upper() == "N":
middle_name = None
break
# is_middle_empty = bool(middle_name)
# print(is_middle_empty)
print("So your full name is {} {} {}? ".format(first_name, '' if middle_name is None else middle_name, last_name))
import time
time.sleep(1)
print("Hmmm..")
time.sleep(1)
just_first = str(input("Should I just call you {}? (y/n) ".format(first_name)))
if just_first.upper() == "Y":
player = first_name
print("Great, nice to meet you", player)
elif just_first.upper() != "Y":
name = first_name, "" if middle_name is None else middle_name, last_name
player = " ".join(name)
print("Sorry about that, let's stick to {} then." .format(player))
print()
#DIRECTION FUNCTION
def getUserDirection():
getUserDirection.counter = 0
getUserDirection.counter += 1
direction = str(input("Which direction do you wish to go? (L/F/R) "))
direction = direction.upper()
if direction not in ("L", "F", "R"):
print("whats does {} mean? You were meant to type 'L', 'F' or 'R'! Try again..".format(direction))
direction = getUserDirection()
elif direction == "L":
print(direction()+counter())
elif direction == "F":
print(direction()+counter())
elif direction == "R":
print(direction()+counter())
return getUserDirection()
#STORY LINES
def start():
print("You have arrived at ... To your left (L) is ..., ahead (F) is ... To your right (R) is ...")
def L1():
print("you go left")
def F1():
print("You continue forward")
def R1():
print("You turn right")
#ADVENTURE-1
adventure = input("So do you fancy a quick adventure? (y/n) ")
if adventure.upper() == "Y":
print("Great then lets set off...")
elif adventure.upper() == "N":
print("Ah well, I guess we can't all be ubercool adventurers like me, fairwell {}, I hope we meet again some day." .format(player))
#ADVENTURE-2
time.sleep(1)
print(start())
print(getUserDirection())错误跟踪
Traceback (most recent call last):
File "C:\Users\admin\PycharmProjects\pythonProject1\main.py", line 70, in <module>
print(getUserDirection())
File "C:\Users\admin\PycharmProjects\pythonProject1\main.py", line 43, in getUserDirection
print(direction()+counter())
TypeError: 'str' object is not callable发布于 2021-01-27 14:07:56
最干净的方法是把你的函数存储在字典中-
def L1():
print("you go left and see...")
def F1():
print("You continue forward and see...")
def R1():
print("You go right and see...")
# define more functions....
inp_to_func = {
'L1': L1,
'F1': F1,
'R1': R1
# define more key-value pairs....
}然后你就可以像-
func = inp_to_func.get(f'{direction}{counter()}')
if not func:
# no function found for input
# do error handling here
pass
else:
func()这假设direction是一个字符串,counter()返回一个数字,并按照显示的顺序组合它们,形成字典中的键。
编辑:如果您有一个counter 变量,而不是一个函数,那么当然您必须执行f'{direction}{counter}'。从您的代码中可以看出,counter是您定义的一个返回数字的函数。
假设direction是一个值为'L'的字符串变量,而counter是一个值为1的int变量。
f'{direction}{counter}'给你'L1'
如果L1是inp_to_func字典中的一个键,并且它的值是一个函数对象,inp_to_func.get('L1')将返回该函数对象。
函数对象现在可以像任何其他函数一样处理,即-它可以使用parens - ()调用。
所以,逐行-
func = inp_to_func.get(f'{direction}{counter}')
# ^ Gets the function object corresponding to the input, or `None`
if not func:
# ^ func was `None` (as in, no key was found)
# no function found for input
# do error handling here
pass
else:
func()
# ^ calls the function发布于 2021-01-27 14:08:18
您可以通过访问globals或使用eval来做到这一点。
direction, counter = "L", 1
globals()[f"{direction}{counter}"]() # globals return a dictionary, where you can access the variable through this dictionary.
eval(f"{direction}{counter}()") # eval evaluates python expression, in this case, the function call这就是你根据你的问题想要的,不过如果我这么做的话.我可能会创建一个函数,然后将direction和counter参数传递给它。
def fun(direction, counter):
if direction == "L":
if counter == 1:
# do something...
elif direction == "R":
# do something...
direction, counter = "L", 1
# then you'll call it like...
fun(direction, counter)https://stackoverflow.com/questions/65920670
复制相似问题