我们有一个功能make_sandwich
,其中包含ingredients
列表,其默认值为['ham', 'ham', 'bacon', 'ham']
def make_sandwich(ingredients=['ham', 'ham', 'bacon', 'ham']):
print("Making a sandwich with ", ingredients)
但是,由于此默认值容易受到this python "mutable default argument" bug feature的影响,我们应该使用不可变的,而不是这样:
def make_sandwich(ingredients=None):
# initialized ingredients here
print("Making a sandwich with ", ingredients)
所以这就是问题所在。我知道有两种方法可以做到这一点,但我不确定哪种方式被认为是更好的做法。
第一个:
if not ingredients:
ingredients = ['ham', 'ham', 'bacon', 'ham']
第二个:
ingredients = ingredients or ['ham', 'ham', 'bacon', 'ham']
我个人经常使用第二个。有时候,我甚至会内联,如果参数只使用一次。例如
print("Making a sandwich with ", ingredients or ['ham', 'ham', 'bacon', 'ham'])
是否有任何理由比其他人更喜欢?
答案 0 :(得分:2)
它们实际上都不是正确的方法。如果你想传递一份空的成分清单怎么办?
更好的解决方案是
if ingredients is None:
ingredients = ['ham', 'ham', 'bacon', 'ham']
答案 1 :(得分:1)
ingredients = ingredients if ingredients else ['ham', 'ham', 'bacon', 'ham']
只取决于谁将阅读您的代码。 我个人对你的第二个
很好ingredients = ingredients or ['ham', 'ham', 'bacon', 'ham']