有什么方法可以知道参数的值是默认值还是用户指定的值? [英] Is there any way to know if the value of an argument is the default vs. user-specified?

查看:21
本文介绍了有什么方法可以知道参数的值是默认值还是用户指定的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找类似于 Lisp 的 arg-supplied-p 变量的东西,以帮助区分默认值和用户指定的相同值.

I'm looking for something that works like Lisp's arg-supplied-p variables, to help differentiate a default value from the same value specified by a user.

示例:

def foo(a=10):
    pass

我想在 foo 中知道它是否是这样调用的:

I'd like to know in foo if it was called like this:

foo()

或者像这样:

foo(10)

甚至像这样:

foo(a=10)

最后两个对我来说是同义词;我不需要知道那个细节.我稍微浏览了检查模块,但 getargspec 为所有 3 次调用返回完全相同的结果.

The last 2 are synonymous enough to me; I don't need to know that detail. I've looked through the inspect module a bit, but getargspec returns exactly the same results for all 3 calls.

推荐答案

除了检查源代码,没有办法区分这三个函数调用——它们意味着相同的含义.如果您需要区分它们,请使用不同的默认值,例如.

Except for inspecting the source code, there is no way to tell the three function calls apart – they are meant to have exactly the same meaning. If you need to differentiate between them, use a different default value, e.g. None.

def foo(a=None):
    if a is None:
        a = 10
        # no value for a provided

这篇关于有什么方法可以知道参数的值是默认值还是用户指定的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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