如何连接 2 个变量,以调用该组合的另一个变量?

How can I concatenate 2 variables, to call another variable of that combination?

我有一个已定义的函数,其中包括一个计数器以了解它已被使用了多少次,并要求用户输入 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

最干净的方法是将函数存储在 dict-

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() return 是一个数字 - 并按所示顺序组合它们形成字典中的键。

编辑:如果你有一个 counter 变量 而不是一个函数 - 你当然必须做 f'{direction}{counter}' 。从您的代码看来,counter 是您定义的函数,return 是一个数字。

假设direction是一个字符串变量,值为'L'counter是一个int变量,值为1

f'{direction}{counter}' 给你 'L1'

如果L1inp_to_func字典中的一个键,它的值是一个函数对象,inp_to_func.get('L1')会return表示函数对象。

函数对象现在可以像任何其他函数一样对待,也就是说 - 它可以使用括号调用 - ().

所以,一行一行-

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

您可以通过访问 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

根据您的问题,这就是您正在寻找的内容,尽管如果我这样做...我可能会创建一个函数,然后将 directioncounter 参数传递给它。

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)