[英]Make function parameters optional
I want the function to return a value when there is an error.我希望 function 在出现错误时返回一个值。 I created this sample code, but it has two parameters.我创建了这个示例代码,但它有两个参数。 How can I make the function parameters optional?如何使 function 参数可选? Because when I run the code below, my IDE returns an error that the parameters are required.因为当我运行下面的代码时,我的 IDE 返回一个错误,需要参数。
def test(error, parameter1):
if parameter1 == True:
print("true")
else:
print("false")
array = []
try:
array[0]
except Exception as e:
error = e
return error
value1 = 1
value2 = 2
if value1 == 1:
#I want this to print the error of the function above
print(test(error))
if value2 == 2:
# I want this to pass parameter to the function above
test(parameter1=True)
Optional paramteters are declared with =None
, ie:可选参数用=None
声明,即:
def test(error=None, parameter1=None):
...
in your function you'll have to check if the parameters are not none, ie:在您的 function 中,您必须检查参数是否不为空,即:
if error is not None:
....
You could set the function parameters some default values so when no parameters are passed, the default values become the values of the variables:您可以为 function 参数设置一些默认值,以便在未传递任何参数时,默认值成为变量的值:
def test(error = None, parameter1 = None):
if parameter1 == True:
print("true")
else:
print("false")
array = []
try:
array[0]
except Exception as e:
error = e
return error
Here None becomes a default value and if a parameter is passed, the value changes from None to the given value.这里 None 成为默认值,如果传递参数,则该值从 None 变为给定值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.