【发布时间】:2018-06-09 19:17:38
【问题描述】:
为了使用字典调用函数,我们使用以下代码:
def f1():
print ("One")
def f2():
print ("Two")
def f3():
print ("Three")
dict = {1: f1, 2: f2, 3: f3}
dict[1]()
最后一行dict[1]() 是如何工作的?
【问题讨论】:
-
dict[1]是f1。所以执行dict[1]()执行f1()。 -
在你创建你的字典之后,这样做:
print(dict[1]),你会看到你会得到类似的东西:<function f1 at 0x101d22e18>。这几乎是您未调用的函数。要真正调用它,这就是你执行()的地方,你会看到你期望的结果。 -
类 NoneType(object) |此处定义的方法:| | __hash__(...) | x.__hash__() 哈希(x) | | __repr__(...) | x.__repr__() repr(x)
-
@eddwinpaz 这让读者很困惑。如果您想提供一个展示代码的答案,请发布答案。把它放在 cmets 中很难破译。
标签: python python-3.x function dictionary