我最近一直在学习 python,我有点困惑为什么人们在调用函数时将参数命名为他们命名的参数?
把这段代码作为入门
def my_funcation(greeting = 'Hello', name = 'Guest'):
return f'{greeting}, {name}. How are you?'
print(my_function('Yo', name = 'Adam'))
一切看起来都不错,但有一部分我不明白。为什么人们指定他们分配给的参数名称?这像是一种约定还是编写好的代码的规则?
为什么我们不能只写这个..
def my_funcation(greeting = 'Hello', name = 'Guest'):
return f'{greeting}, {name}. How are you?'
print(my_function('Yo', 'Adam'))
IMO,第二个更好,以防参数名称发生变化。
最佳答案
有时,它会为代码添加有用的上下文。
你想读什么:
enumerate('xyz', 120) # err...what does that second arg do again?
或
enumerate('xyz', start=120) # oh yeah, the start index
它允许您修改或重新排序函数的 kwargs,而无需更改调用代码。
考虑在前面添加一个新参数:
def my_function(color='red', greeting='Hello', name='Guest'):
...
如果你不修改调用者 my_function('Yo', 'Adam')
,你现在会让他们填充不正确的参数 - 如果你没有一个好的测试覆盖率,您甚至可能直到为时已晚才注意到该错误。
关于Python:我们什么时候应该命名我们传递的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51428918/