Python return空值的几种情况

1,191 阅读1分钟

Return None

当该函数没有其他返回值时不会用到return None,只有有其他不为None的返回值才会用到。

def get_mother(person):
    if is_human(person):
        return person.mother
    else:
        return None

Return

类似循环里的break,只是为了不再继续执行下面的语句。

def find_prisoner_with_knife(prisoners):
    for prisoner in prisoners:
        if "knife" in prisoner.items:
            prisoner.move_to_inquisition()
            return # no need to check rest of the prisoners nor raise an alert
    raise_alert()

no return at all

类似于c++和Java里的void, 用在以下的情况:当前函数的返回值没有任意意义 or 不需要被catch到的时候。

def set_mother(person, mother):
    if is_human(person):
        person.mother = mother

参考Stack Overflow的链接:stackoverflow.com/questions/1…