在以艰难的方式学习Python (http://learnpythonthehardway.org/book/ex39.html)的练习39中,定义了以下函数(get_slot()
和get()
):
def get_slot(aMap, key, default=None):
"""
Returns the index, key, and value of a slot found in a bucket.
Returns -1, key, and default (None if not set) when not found.
"""
bucket = get_bucket(aMap, key)
for i, kv in enumerate(bucket):
k, v = kv
if key == k:
return i, k, v
return -1, key, default
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
为什么在致电default=default
时写get_slot()
?
在我看来,只需用{'默认'会足够吗? - > get_slot()
get_slot(aMap, key, default)
是否与命名与位置函数参数有关? (如下所述:http://pythoncentral.io/fun-with-python-function-parameters/)
或default=default
是完全由于其他原因而完成的?
答案 0 :(得分:1)
default
是函数get_slot()
的“关键参数”,默认值为None。
当您在未指定“默认”的情况下致电get_slot()
时,其值为“无”。
在上面的示例中,您将关键参数“default”设置为“default”,这是传递给函数“get”的参数,因此它取值None
。
所以在这种特殊情况下,不管你是否打电话都不会改变:
get_slot(aMap, key)
或
get_slot(aMap, key, default = default)
但如果将None
的{{1}}函数传递给get
函数,则default
函数中的get_slot
变量将采用与None
不同的值
我希望这有点清楚。