python - 如何连接 2 个变量,以调用该组合的另一个变量?
问题描述
我有一个定义的函数,其中包括一个计数器,以了解它已使用了多少次,并要求用户输入 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
解决方案
最干净的方法是将你的函数存储在一个字典中-
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
一个int
值为 的变量1
。
f'{direction}{counter}'
给你'L1'
如果L1
是inp_to_func
字典中的键且其值为函数对象,inp_to_func.get('L1')
则返回该函数对象。
函数对象现在可以像任何其他函数一样对待,即 - 可以使用括号调用 - ()
。
所以,一行一行地——
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
推荐阅读
- javascript - 如何摆脱 D3JS 中的嵌套 selectAll?
- elixir - ecto 变更集为现有添加关联
- python - dask 数组分块如何用于三个或更多维度?
- python - 如何在 python pandas 中找到两组之间的差异?
- java - 具有本地文件依赖项的 Maven 项目构建错误 501
- r - 编码这个适应度函数的最快方法是什么?
- ios - 有没有办法检查 NSPhotoLibraryAddUsageDescription 权限是被授予还是被拒绝?
- android - 如何使用 Boost Asio 在 Android 上获取我的本地 udp ip 地址?
- javascript - 输入后如何过滤json?
- r - R中的列选择错误与应用循环