为什么在Python的函数中使用None作为哨兵?
版本1为什么在Python的函数中使用None作为哨兵?,python,function,sentinel,Python,Function,Sentinel,版本1 def add_author(authors_books, current_books=None): if current_books is None: current_books = [] current_books.extend(authors_books) return current_books 版本2 def add_author(authors_books): current_books = [] current_books.extend(au
def add_author(authors_books, current_books=None):
if current_books is None:
current_books = []
current_books.extend(authors_books)
return current_books
版本2
def add_author(authors_books):
current_books = []
current_books.extend(authors_books)
return current_books
在版本1中,如果可以使用版本2中的函数获得相同的结果,为什么要使用“current_books=None”和下面的“if”语句
在某些用例中,您是否会将参数设置为=to None?例如,在编写递归函数时,该函数必须传递一些可变的内容,如列表。玩具示例:
def foo(collected=None, level=0, max_depth=3):
if collected is None: # first call!
collected = []
collected.append(level)
print(collected)
if level < max_depth:
foo(collected, level + 1, max_depth)
foo()
# output:
# [0]
# [0, 1]
# [0, 1, 2]
# [0, 1, 2, 3]
当第二次调用
add_author
时,我们可能不想将当前_books
初始化为空列表,也许?但如果我们提供collected=[],它将实现相同的结果?@Gojilla correct。但是,当参数只有一个值可接受时,您不希望强制用户提供该参数。
def foo(collected=[], level=0, max_depth=3):
collected.append(level)
print(collected)
if level < max_depth:
foo(collected, level + 1, max_depth)
foo()
# output:
# [0]
# [0, 1]
# [0, 1, 2]
# [0, 1, 2, 3]
foo()
# output:
# [0, 1, 2, 3, 0]
# [0, 1, 2, 3, 0, 1]
# [0, 1, 2, 3, 0, 1, 2]
# [0, 1, 2, 3, 0, 1, 2, 3]