如何“忽略”参数

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

How to "ignore" arguments

问题

我正在用Python制作一个任务管理器,它使用一个JSON文件作为存档,并保存用户提供给程序的信息。我创建了一个包含不同函数的Python文件来管理这些输入。

当收集到信息后,我创建了一个函数将这些信息添加到JSON文件中。

import json

def setTitle():
    # 收集用户输入

    appendJson(task=userInput)

def setDescription():
    # 收集用户输入

    appendJson(description=userInput)

def appendJson(task, description):
    # 生成JSON项

当我运行代码时,会出现错误,因为我没有提及其他参数。
所以基本上我应该写成appendJson(task=userInput, description=bla bla),问题是如果我这样写,代码就无法工作。

那么有没有办法在函数调用中省略第二个参数?

如果你对某些地方不理解,请在评论中告诉我。
谢谢 <3

英文:

I'm making a task manager in python that uses a json file as an archive and to save the informations that the user gives to the program i made a python file with different functions that manages those inputs.

And then when the infos are collected I made a function that adds those infos to the json file

import json

def setTitle():
    #collects user&#39;s input

    appendJson(task=userInput)

def setDescription():
     #collects user&#39;s input

     appendJson(description=userInput)

def appendJson (task, description):
     #generate the json item

When I run the code it gives me an error because I didn't mention the other arguments.
So basically I should've wrote appendJson(task=userInput, description=bla bla) and the problem is that the code doesn't work if I wrote that.

So is there a way to omit the second argument in the function call?

If you did not understand something tell me in the comments
Thanks <3

答案1

得分: 1

如果你想在调用函数时不必每次都提供每个参数,你可以使用关键字参数:

def appendJson(task, description=None):
    # 生成json项

在这种情况下,第一个参数将始终被解释为task,你可以选择通过appendJson(task, description="randomdescription")来提供description

如果你想让两个参数都是可选的,你可以将两个参数都设置为关键字参数:

def appendJson(task=None, description=None):
    # 生成json项
英文:

If you want to be able to call the function without having to provide every argument each time, you can use a keyword argument instead:

def appendJson(task, description=None):
     #generate the json item

In that case, the first argument will always be interpreted as task and you can optionally supply description via appendJson(task, description="randomdescription").

If you want to have both optional, you can make both arguments a keyword argument:

def appendJson(task=None, description=None):
     #generate the json item

答案2

得分: 1

修复了,

给参数分配一个默认值,像这样:

def appendJson(task="默认值", description="默认值"):

你也可以使用

def appendJson(task="Hello World", description=None):
英文:

Fixed it,

Assing a default value to the arguments like this:

def appendJson(task=&quot;default value&quot;, descripiton=&quot;defaultvalue&quot;):

You can also use

def appendJson(task=&quot;Hello World&quot;, descripiton=None):

huangapple
  • 本文由 发表于 2023年8月8日 22:13:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76860406.html
匿名

发表评论

匿名网友

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

确定