-1

我从PEP 532中发现了以下陈述:

  • __else__if是由于缺少尾随else子句而导致的表达式短路结果
  • __then__else是由于缺少前导if子句而导致的表达式短路结果

这些陈述是什么意思?有什么例子可以更清楚地说明这些观点吗?

4

1 回答 1

3

您似乎正在阅读(关于)PEP 532 - A Circuit Breaking Operator and Protocol,建议让左侧操作数访问短路操作。

Python 目前没有办法挂钩orand布尔运算符;这些运算符的短路在于如果可以从左侧操作数确定结果,则不需要计算右侧操作数表达式。

例如,以下表达式不会引发异常:

count = 0
average = count and total / count

即使右边的表达式ZeroDivisionError在运行时会引发异常。

PEP 提出了一个新的运算符,elseoperator,它将让左侧的类根据它的真值来处理运算的结果。所以在表达式中

lefthand else righthand

该类lefthand 可以访问lefthandrighthand取决于bool(lefthand).

您没有提供您找到的语句的完整上下文,但 PEP 532 是定义__else__and__then__方法的提案;type(lefthand).__then__(lefthand)lefthand被认为是真的时被调用,否则type(lefthand).__else__(righthand)被调用:

result = type(lefthand).__then__(lefthand) if lefthand else type(lefthand).__else__(lefthand, righthand)

您可以将这些实现为

class CircuitBreaker:
    def __bool__(self):
        # am I true or false?
        return someboolean

    def __then__(self):
        # I'm true, so return something here
        return self

    def __else__(self, righthand):
        # I'm false, the righthand has been evaluated and pass ed in
        return righthand

请注意,PEP 532仍在讨论中,并且可能永远不会实施此提案。

于 2016-12-06T22:18:23.750 回答