【发布时间】:2012-09-17 19:31:01
【问题描述】:
对于形参密切相关的函数,如
def add_two_numbers(n1, n2):
return n1 + n2
def multiply_two_numbers(n1, n2):
return n1 * n2
如上所示,为两个函数中的参数赋予相同的名称是否是个好主意?
另一种方法是重命名函数之一中的参数。例如:
def add_two_numbers(num1, num2):
return num1 + num2
在两个函数中保持相同看起来更一致,因为每个函数采用的参数是相似的,但这更令人困惑吗?
同样,下面的例子哪个更好?
def count(steps1, steps2):
a = 0
b = 0
for i in range(steps1):
a += 1
for j in range(steps2):
b += 1
return a, b
def do_a_count(steps1, steps2):
print "Counting first and second steps..."
print count(steps1, steps2)
否则,更改第二个函数中的参数会给出:
def do_a_count(s1, s2):
print "Counting first and second steps..."
print count(s1, s2)
同样,我有点不确定哪种方式最好。保持相同的参数名称使两个函数之间的关系更清晰,而第二个意味着两个函数中的参数没有混淆的可能性。
我进行了一些搜索(包括浏览 PEP-8),但找不到明确的答案。 (我发现的类似问题包括: Naming practice for optional argument in python function 和 In Python, what's the best way to avoid using the same name for a __init__ argument and an instance variable?)
【问题讨论】:
-
"而第二个意味着不可能混淆两个函数中的参数。"你能举一个你担心的那种混乱的例子吗?
-
在这些情况下,将它们混淆的可能性不大(也许这通常是真的......)我想我更多地考虑使用与变量参数相同的名称,这可能这不是个好主意。
标签: python coding-style naming-conventions