在 Python 3.8 中,"return"本身等同于"return(None)&quo



我刚刚看到了下面的Python代码,我对第一个return有点困惑。默认情况下它会返回None吗?等同于return(None)吗?如果执行第一个return,函数inner()自动结束,第二个return单独保留吗?

def smart_check(f):
def inner(a,b):
if b==0:
print("illegit: b =", b)
return   # the first return
return(f(a,b))
return(inner)
@smart_check
def divide(a,b):
return(a/b)

默认情况下它是否返回 None ?是否等同于返回(无(

是,请参阅文档:如果存在表达式列表,则对其进行计算,否则"无"是 替代

如果执行第一个返回,函数 inner(( 自动到此结束,第二次返回独自一人?

是的


如果你不想返回任何内容,你甚至可以完全删除 return 语句:

def smart_check(f):
def inner(a,b):
if b != 0:
return f(a,b)
print("illegit: b =", b)
return(inner)

由于 print 不返回任何内容,您甚至可以将此函数重写为

def smart_check(f):
def inner(a,b):
return f(a,b) if b!=0 else print("illegit: b =", b)
return(inner)

相关内容

最新更新