Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 抽象if语句并由函数返回_Python_Python 2.7 - Fatal编程技术网

Python 抽象if语句并由函数返回

Python 抽象if语句并由函数返回,python,python-2.7,Python,Python 2.7,我有这样一个函数: def test(): x = "3" # In actual code, this is computed if x is None: return None y = "3" if y is None: return None z = "hello" if z is None: return None def test(): x = "3" check

我有这样一个函数:

def test():
    x = "3" # In actual code, this is computed

    if x is None:
        return None

    y = "3"

    if y is None:
        return None

    z = "hello"

    if z is None:
        return None
def test():
    x = "3"
    check_None(x)

    y = "3"
    check_None(y)

    z = "hello"
    check_None(z)
是否有一种方法可以使
if
语句消失,并用一些函数将其抽象出来。我期待着这样的事情:

def test():
    x = "3" # In actual code, this is computed

    if x is None:
        return None

    y = "3"

    if y is None:
        return None

    z = "hello"

    if z is None:
        return None
def test():
    x = "3"
    check_None(x)

    y = "3"
    check_None(y)

    z = "hello"
    check_None(z)
理想情况下,
check\u None
应该在传递给它的参数为None时改变控制流。这可能吗


注意:在Python2.7上工作。

您可以很容易地用这样的代码编写它

def test():
    #compute x, y, z
    if None in [x, y, z]:
       return None
    # proceed with rest of code
更好的方法是使用生成器生成值x、y、z,以便一次只计算一个值

def compute_values():
    yield compute_x()
    yield compute_y()
    yield compute_z()

def test():
    for value in compute_values():
        if value is None:
           return None

我不确定我们是否应该这样做,但其中一个黑客可能是这样的,也可以创建自己的异常类,只捕获特定的异常,这样exception就不会意外捕获其他异常并返回None

class MyException(Exception):
    pass

def check_none(x):
    if x is None:
        raise MyException

def test():
    try:
        z=None
        check_none(z)
    except MyException, e:
        return None

return_value = test()

只有当
check\u None
引发了
test
无法捕获的异常时,它才能强制
test
返回None@jornsharpe Ok,我想我明白了。是
test
没有捕捉到它。
z
是否依赖于
y
y
是否依赖于
x
?顺便说一句,我知道这只是语义,但是如果
不是循环,你可以在一行上写,如果这让你更快乐的话。@cdarke是的,它们取决于你。在某些情况下,他们没有。但是我只想避免if检查,并将其抽象到函数上。好吧,那么在计算中如何生成
None
?它是由模块中的其他函数返回的吗?这意味着您必须首先进行计算。如果
x
y
解析为
None
,您就不会提前退出。这就是为什么我建议使用Generator而不是
for
循环,如果(x,y,z)中没有,您只需执行
:返回None
Ok,这样更好,但在生成器解决方案中,我想我必须使用一个循环。如果您觉得我的解决方案有用,请将其标记为正确。不要将异常用于流控制-@julka我实际上可以使用异常来实现我想要的。但是在这个解决方案中,我希望
check_none
返回none,并且不希望
尝试除
块之外的其他块。@Sibi:这就是异常处理的真正目的。@Sibi除了函数之外,您不想尝试,对吗?里面的功能可以吗?