python - 函数返回变量而不是变量的赋值
问题描述
我在 Python 中有一个相当简单的代码(见下文),但无法弄清楚为什么“选择”变量不返回分配的变量全局值而不是函数中的变量。例如,如果我运行函数“drink_coffee”,当我选择“a”时,返回的值应该是“cappuccino”。相反,它返回“a”。但是如果我从函数中打印“a”,它会返回“cappuccino”。有什么我想念的想法吗?
a = 'cappuccino'
b = 'espresso'
c = 'latte'
def drink_coffee():
'''Returns the coffee the user would like to drink'''
global a, b, c
selection = input("What would you like to drink? A: cappuccino, B: espresso, C:latte? ").lower()
print(selection)
print(a)
return selection
喝咖啡()
解决方案
内容为字母的字符串a
与包含某些内容的名为 a 的变量之间存在差异。
在您的代码中,您将用户输入分配给变量,该变量selection
将包含用户输入的任何字符串。
我认为您在这里想要的是将您的字母到饮料的映射存储在字典中。它可能看起来像这样:
drink_mappings = { "a" : 'cappuccino',
"b" : 'espresso',
"c" : 'latte' }
然后,当用户提供 a、b 或 c 字符串时,您可以使用drink_mappings
字典解析并返回映射的饮料名称:
例如
def drink_coffee():
'''Returns the coffee the user would like to drink'''
selection = input("What would you like to drink? A: cappuccino, B: espresso, C:latte? ").lower()
print(drink_mappings.get(selection, "Nothing") )
print(a)
return drink_mappings.get(selection, "Nothing")
这应该给你你想要的行为。不过一般来说,您通常不能使用通过用户输入输入的字符串值直接引用变量名。虽然可以使用一些自省代码 - 但这可能不是这类事情的最佳用途。出于兴趣,这可能是如何工作的:
def drink_coffee():
'''Returns the coffee the user would like to drink'''
global a, b, c
selection = input("What would you like to drink? A: cappuccino, B: espresso, C:latte? ").lower()
print(selection)
print(a)
return globals()[selection]
它使用包含globals()
所有当前活动全局变量的字典,并允许您通过与其名称匹配的字符串来引用它们。locals()
如果您不喜欢使用全局变量,那么有一个类似的内置字典会做类似的事情。
但这是一件非常奇怪的事情,如果他们看到这样的用例,人们会难以置信地眯起眼睛。例如,任何运行此代码的用户都可以通过键入其名称来访问当前处于活动状态的任何变量或函数。这会引发一些严重的安全问题,并且会被认为是一个非常大的禁忌。
推荐阅读
- python - 此代码如何比较列表中的数字并输出最大值?
- ruby-on-rails - 如何在 Rails 3.2 中将兔子作业作为后台进程运行
- java - 获取锁定的智能手表屏幕上的“点击”次数
- javascript - 如何构建 AlphaTab?
- c# - DataGridView 的宽度属性总是返回 NULL
- c++ - OMP 并行化在可变 CRTP 类中不起作用
- android - 为什么 gradle 没有签署我的工件
- python - 帆布,一条尾巴较细的线条
- javascript - 异步处理程序在 unhandledRejection 上开玩笑(反应)失败
- java - 自定义对象从嵌入式 FX (JFXPanel) 拖放到 Swing