这是我的第一个问题,请保持温柔。
如问题所述,我在 LPTHW Ex。 39. 我需要帮助来理解 get
函数中的默认变量。我想我不太明白为什么它被定义为 default=None
作为参数(或者为什么 get_slot
函数做了同样的事情)并使用参数 default =default
当它剥离 v
时返回以供以后在 ex39_test.py
我可以毫不费力地找到其他任何事情的答案。这看起来很简单,但没有其他来源明确说明这个问题。
供引用: The LPTHW Ex. 39 can be read here.
我感到困惑的部分涉及 hashmap.py
中的这部分代码:
def get(aMap, key, default=None):
"""Gets the value in a bucket for the given key, or the default."""
i, k, v = get_slot(aMap, key, default=default)
return v
我了解该函数的作用,并且了解大部分功能。不过,这种默认设置让我很困惑。我还想尽可能多地了解原因,以便该概念在将来有用。
请 ELI5。
注意:我假设 ex39_test.py
最后一部分中的 'Does Not Exist'
(调用此函数的唯一部分)是 (re? )设置(?)默认值,但我不确定这是正确或完整的。
再次供引用:
city = hashmap.get(cities, 'TX', 'Does Not Exist')
print "The city for the state 'TX' is: %s" % city
最佳答案
您正在使用调用者传递给 get
函数的默认值(即 default
)来调用 get_slot
。如果调用者没有传递任何内容,则 default
为 None
,但如果他们确实传递了任何内容,则您希望传递任何内容,而不是总是传递 无
。
关于Python:LPTHW 示例。 39、获取函数,默认变量。 ELI5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28554265/