是否可以用if语句编写单行返回语句?

2024-06-07 04:06:08 发布

您现在位置:Python中文网/ 问答频道 /正文

在python中可以从单行方法返回

找这样的东西

return None if x is None

上面试过了,它是无效语法

我很容易做到:

if x is None:
    return None

但我只是好奇能否把上面的if语句合并成一行


Tags: 方法nonereturnifis语法语句单行
3条回答

可以在一行上编写标准的“if”语句:

if x is None: return None

但是pep 8 style guide建议不要这样做:

Compound statements (multiple statements on the same line) are generally discouraged

免责声明:不要这样做。如果你真的想要一个一行,然后像Nakedfanic说,打破经验法则从PEP-8。然而,它说明了为什么return没有像你想象的那样表现,以及一个事物看起来是什么样子,确实像你想象的return那样表现。

不能说return None if x is None的原因是return引入了一个语句,而不是一个表达式。所以没有办法把它括起来。

没关系,我们可以解决。让我们编写一个函数ret,它的行为类似于return,只是它是一个表达式,而不是一个完整的语句:

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)

是的,它被称为conditional expression

return None if x is None else something_else

你需要一个else something在条件中才能工作。

相关问题 更多 >