以下函数(用 Python 实现)的好名称是什么?
def a_function(element, a_set):
if a_set[0] == element:
return a_set[1]
if a_set[1] == element:
return a_set[0]
assert 'A' == a_function('B', ['A', 'B'])
最佳答案
我会使用不同的函数名称、不同的参数名称和文档字符串来清楚地说明发生了什么,例如:
def get_other(current, both):
"""Return the element from 'both' that is not 'current'."""
...
请注意both
暗示一对没有任何冗长的内容,并且不指定 type
必填。
您可以使用您自己的实现或 Joel 的实现;只要函数按照它所说的去做,它的实现方式并不重要(除非性能问题、边缘情况等)。
但是,要使用不可索引的容器(例如 set
或 dict
的键),无需显式测试 both
的内容。是的,我可能会选择:
def get_other(current, both):
"""Return the element from 'both' that is not 'current'."""
for item in both:
if item != current:
return item
确实,如果 len(both) > 2
,这只会返回其中第一个不等于 current
的项目- 如果这不是所需的行为,您可以为此添加检查。
关于python - 如何命名一个以对象 `A` 和集合 `{A, B}` 作为参数,然后返回 `B` 的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23179672/