Python 将 None 传递给参数是否正确?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28569551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it correct to pass None to a parameter?
提问by
I am trying to understand if it is a good idea or not to pass as parameter the python equivalent of null; which I believe is None.
我试图了解将 Python 等价的 null 作为参数传递是否是一个好主意;我相信是无。
Example: You have a function that accepts n parameters; in one case I need just the first and second parameters, so instead of writing a long function definition with args and kwargs, and manipulate them, I can just pass null to one of the parameters.
示例:您有一个接受 n 个参数的函数;在一种情况下,我只需要第一个和第二个参数,因此无需使用 args 和 kwargs 编写长函数定义并操作它们,我只需将 null 传递给其中一个参数即可。
def myfunct(a, b, c[optional], d[optional], e, f....n):
[do something]
if d=="y":
[do something but use only a and b]
Execution:
执行:
myfunct(a, b, c, d, .....n) #OK!
myfunct(a, b, None, "y", None,....n) #OK?
This theoretically should not raise an error, since null is a value I believe (this is not C++), although I am not sure if this is a correct way to do things. The function knows that there is a condition when one of the parameters is a specific value, and in that case, it won't ask for any other parameter but 1; so the risk of using null should be practically 0.
从理论上讲,这不应该引发错误,因为我相信 null 是一个值(这不是 C++),尽管我不确定这是否是正确的做事方式。该函数知道当参数之一是特定值时存在条件,在这种情况下,它不会要求任何其他参数,而是 1;所以使用 null 的风险实际上应该是 0。
Is this acceptable or am I potentially causing issues down the road, using this approach?
使用这种方法,这是可以接受的,还是我可能会导致问题?
采纳答案by rlbond
There's nothing wrong with using None to mean "I am not supplying this argument".
使用 None 表示“我没有提供这个论点”并没有错。
You can check for None in your code:
您可以在代码中检查 None :
if c is None:
# do something
if d is not None:
# do something else
One recommendation I would make is to have None be the default argument for any optional arguments:
我要提出的一项建议是将 None 作为任何可选参数的默认参数:
def myfunct(a, b, e, f, c=None, d=None):
# do something
myfunct(A, B, E, F)