Skip to main content
 首页 » 编程设计

python之对于可能返回 None 的方法,哪种返回方式是 "better"

2025年05月04日12zhwl

如果查找失败,我有一个方法将返回一个对象或 None。以下哪种风格比较好?

def get_foo(needle): 
    haystack = object_dict() 
    if needle not in haystack: return None 
    return haystack[needle] 

或者,

def get_foo(needle): 
    haystack = object_dict() 
    try: 
        return haystack[needle] 
    except KeyError: 
        # Needle not found 
        return None 

我自己也不确定哪个更受欢迎。另一种选择是 return haystack[needle] if needle in haystack else None,但我不确定这是否更好。

请您参考如下方法:

对于这个特定的例子,它看起来像 dict 方法 get是最简洁的:

def get_foo(needle): 
    haystack = object_dict() 
    return haystack.get(needle) 

一般来说,在 Python 中,人们倾向于使用 try/except 而不是先检查某些东西 - 请参阅 EAFP在 glossary 中输入.请注意,许多“成员资格测试”功能在幕后使用异常。

我不会就多次返回或替代方案的相对优点展开激烈的争论:)