当将函数用作默认参数时,为什么该函数总是被调用?

huangapple go评论87阅读模式
英文:

When using a function as a default argument, why is that function always called?

问题

我想要一个函数,可以在有或没有参数的情况下调用它,并且在参数缺失时使用另一个函数来获取参数值。

我已经尝试了以下代码:

def GetValue():
...

def Process(value=GetValue):
...

我尝试使用Process()Process(105)来调用函数Process,但无论哪种方式,它都调用了函数GetValue

英文:

I want to have a function that I can call it with or without an argument, using another function to get the argument value in case it is missing.

I already tried this:

def GetValue():
...

def Process (value = GetValue):
...

I tried to call the function Process with Process() and Process(105) but it called the function GetValue either way.

答案1

得分: 2

def行上的任何内容在函数定义时执行。你想要在Process函数内部调用GetValue,这样只有在满足特定参数值的条件时才会调用它:

def GetValue():
    ...

def Process(value = None):
    if value is None:
        value = GetValue()
    ...
英文:

Anything on the def line is executed when the function is defined. You want to call GetValue inside the Process function so that it’s only called when the condition is met for a specific argument value:

def GetValue():
    ...

def Process(value = None):
    if value is None:
        value = GetValue()
    ...

huangapple
  • 本文由 发表于 2023年8月9日 11:43:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76864428.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定