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