如何将参数默认设置为 python
How to keep the parameter by default on python
我知道可以给函数传参,也可以不带参调用函数:
def printWords(text1="a", text2="b"):
print('The text1 is "%s" and text2 is "%s"' % (text1,text2))
printWords()
那么,我们就可以得到结果了
The text1 is "a" and text2 is "b"
我们也可以传递结果来覆盖默认参数
printWords("Apple") // The text1 is "Apple" and text2 is "b"
printWords("Apple","Banana") // The text1 is "Apple" and text2 is "Banana"
那我只想改text2
怎么办?
在这种情况下,我们可以将 a
传递给函数。
但是如果参数很多,文本很长,那就太乱了,例如:
def curlSomthing(sslKey="MIICXAIBAAKBgQCRq88qPiw..............=",someText="BuDPuTMSUrwnophwzti8HRc6Z7SYaGnFHMVMrF/3f/TgdWd4UTH3397RA7m5I4gVNbFCA0xOTfh............",someSetting=False):
....
....
....
....
我们无法在每次调用函数时复制并粘贴所有参数。
我知道这不是定义函数的好方法。
但是在我公司的代码中有很多这样的功能。我无法更改所有功能
有什么解决办法吗?
只需将参数名称指定为关键字参数即可:
printWords(text2="Apple")
那么text1
将保持不变。
用你的其他乱七八糟的函数:
curlSomthing(someText="foo bar")
我知道可以给函数传参,也可以不带参调用函数:
def printWords(text1="a", text2="b"):
print('The text1 is "%s" and text2 is "%s"' % (text1,text2))
printWords()
那么,我们就可以得到结果了
The text1 is "a" and text2 is "b"
我们也可以传递结果来覆盖默认参数
printWords("Apple") // The text1 is "Apple" and text2 is "b"
printWords("Apple","Banana") // The text1 is "Apple" and text2 is "Banana"
那我只想改text2
怎么办?
在这种情况下,我们可以将 a
传递给函数。
但是如果参数很多,文本很长,那就太乱了,例如:
def curlSomthing(sslKey="MIICXAIBAAKBgQCRq88qPiw..............=",someText="BuDPuTMSUrwnophwzti8HRc6Z7SYaGnFHMVMrF/3f/TgdWd4UTH3397RA7m5I4gVNbFCA0xOTfh............",someSetting=False):
....
....
....
....
我们无法在每次调用函数时复制并粘贴所有参数。 我知道这不是定义函数的好方法。 但是在我公司的代码中有很多这样的功能。我无法更改所有功能
有什么解决办法吗?
只需将参数名称指定为关键字参数即可:
printWords(text2="Apple")
那么text1
将保持不变。
用你的其他乱七八糟的函数:
curlSomthing(someText="foo bar")