非标准的可选参数默认值 [英] Non-Standard Optional Argument Defaults

查看:159
本文介绍了非标准的可选参数默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个功能:

def f(a,b,c=g(b)):
    blabla

def g(n):
    blabla

c是函数f中的可选参数.如果用户未指定其值,则程序应计算g(b),该值将为c.但是代码无法编译-它说未定义名称"b".该如何解决?

c is an optional argument in function f. If the user does not specify its value, the program should compute g(b) and that would be the value of c. But the code does not compile - it says name 'b' is not defined. How to fix that?

有人建议:

def g(b):
    blabla

def f(a,b,c=None):
    if c is None:
        c = g(b)
    blabla

但这不起作用.也许用户希望c设置为None,然后c将具有另一个值.

But this doesn't work. Maybe the user intended c to be None and then c will have another value.

推荐答案

def f(a,b,c=None):
    if c is None:
        c = g(b)

如果None可以是c的有效值,则可以执行以下操作:

If None can be a valid value for c then you do this:

sentinel = object()
def f(a,b,c=sentinel):
    if c is sentinel:
        c = g(b)

这篇关于非标准的可选参数默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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