class ReturnValue(Exception):
def __init__(self, value):
Exception.__init__(self)
self.value = value
def enable_ret(func):
def decorated_func(*args, **kwargs):
try:
return func(*args, **kwargs)
except ReturnValue as exc:
return exc.value
return decorated_func
def ret(value):
raise ReturnValue(value)
@enable_ret
def testfunc(x):
ret(None) if x is None else 0
# in a real use-case there would be more code here
# ...
return 1
print testfunc(None)
print testfunc(1)
可以在一行上编写标准的“if”语句:
但是pep 8 style guide建议不要这样做:
免责声明:不要这样做。如果你真的想要一个一行,然后像Nakedfanic说,打破经验法则从PEP-8。然而,它说明了为什么
return
没有像你想象的那样表现,以及一个事物看起来是什么样子,确实像你想象的return
那样表现。不能说
return None if x is None
的原因是return
引入了一个语句,而不是一个表达式。所以没有办法把它括起来。没关系,我们可以解决。让我们编写一个函数
ret
,它的行为类似于return
,只是它是一个表达式,而不是一个完整的语句:是的,它被称为conditional expression:
你需要一个
else something
在条件中才能工作。相关问题 更多 >
编程相关推荐