英文:
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()
...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论