以艰难的方式学习 Python ex39 [英] Learn Python the Hard Way ex39

查看:41
本文介绍了以艰难的方式学习 Python ex39的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Learn Python the Hard Way (http://learnpythonthehardway.org/book/ex39.html),定义了以下函数(get_slot()get()):

In exercise 39 of Learn Python the Hard Way (http://learnpythonthehardway.org/book/ex39.html), the following functions are defined (get_slot() and 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 ?

Why write default=default when calling get_slot() ?

在我看来,简单地使用default"调用 get_slot() 就足够了?-> get_slot(aMap, key, default)

It would seem to me that simply calling get_slot() with 'default' would be sufficient? -> get_slot(aMap, key, default)

default=default 是否与命名函数参数和位置函数参数有关?(正如这里所讨论的:http://pythoncentral.io/fun-with-python-函数参数/)还是 default=default 完全出于不同的原因?

Is the default=default something to do with named vs positional function parameters? (as are discussed here: http://pythoncentral.io/fun-with-python-function-parameters/) or is the default=default done for a different reason entirely?

推荐答案

default 是函数 get_slot() 的关键参数",默认值为 None.当您调用 get_slot() 而不指定default"时,它采用值None".在上面的示例中,您将关键参数default"设置为default",这是传递给函数get"的参数,因此它的值为 None.

default is a "key argument" for function get_slot() and its default value is None. When you call get_slot() without specifying "default", it takes the value "None". In the example above you're setting the key argument "default" to "default" which is the argument passed to the function "get", so it takes value None.

因此,在这种特殊情况下,您是否调用都不会改变:

So in this particular case it doesn't change whether you call:

get_slot(aMap, key)

get_slot(aMap, key, default = default)

但是如果将不同于 None 的值传递给 get 函数,则 get_slot 中的 default 变量函数将采用与 None 不同的值.

but if a value different from None was passed to the get function the default variable in your get_slot function would take a value different from None.

我希望这能让我明白一点.

I hope this clears it a bit.

这篇关于以艰难的方式学习 Python ex39的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆