在艰难地学习 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
为什么调用get_slot()时要写default=default?
在我看来,简单地使用“默认”调用 get_slot() 就足够了吗? -> get_slot(aMap, key, default)
default=default 是否与命名函数参数和位置函数参数有关? (正如此处所讨论的:http://pythoncentral.io/fun-with-python-function-parameters/) 还是 default=default 完全出于不同的原因?
请您参考如下方法:
default 是函数 get_slot() 的“关键参数”,其默认值为 None。 当您调用 get_slot() 时未指定“default”,它的值为“None”。 在上面的示例中,您将键参数“default”设置为“default”,这是传递给函数“get”的参数,因此它的值为 None。
因此在这种特殊情况下,您是否调用都不会改变:
get_slot(aMap, 键)
或
get_slot(aMap, key, default = default)
但如果将不同于None 的值传递给get 函数,get_slot 中的default 变量函数将采用不同于 None 的值。
我希望这能稍微清除它。
