oob*_*boo 4 python optional-arguments
我有两个功能:
def f(a,b,c=g(b)):
blabla
def g(n):
blabla
Run Code Online (Sandbox Code Playgroud)
c是函数中的可选参数f.如果用户没有指定其值,程序应该计算g(b),这将是值c.但是代码没有编译 - 它说名称'b'没有定义.如何解决?
有人建议:
def g(b):
blabla
def f(a,b,c=None):
if c is None:
c = g(b)
blabla
Run Code Online (Sandbox Code Playgroud)
但这不起作用.也许用户打算c成为None,然后c会有另一个值.
Pao*_*ino 26
def f(a,b,c=None):
if c is None:
c = g(b)
Run Code Online (Sandbox Code Playgroud)
如果None可以是有效值,c则执行以下操作:
sentinel = object()
def f(a,b,c=sentinel):
if c is sentinel:
c = g(b)
Run Code Online (Sandbox Code Playgroud)