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

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

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

问题

我想要一个函数我可以带或不带参数调用它如果缺少参数可以使用另一个函数来获取参数值

我已经尝试过这样做

```python
def GetValue():
...

def Process(value = GetValue):
...

我尝试调用函数 Process 分别用 Process()Process(105),但它都调用了函数 GetValue


<details>
<summary>英文:</summary>

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. 

</details>


# 答案1
**得分**: 2

```python
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-2.html
匿名

发表评论

匿名网友

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

确定