【问题标题】:Set operator precedence设置运算符优先级
【发布时间】:2019-02-17 16:24:14
【问题描述】:

在 python 中,我无法理解运算符的优先级。

a = set([1, 2, 3])

a|set([4])-set([2])

上面的表达式返回 {1,2,3,4}。但是,我认为运算符 |应该在之前执行 - 但这似乎不会发生。

当我应用括号时,它会返回我想要的输出,即 {1,3,4}

  (a|set([4]))-set([2])

所以,我的问题是为什么会发生这种情况,以及在应用集合操作时,运算符(对于 -、|、&、^ 等集合运算符)的优先级是什么。

【问题讨论】:

标签: python python-3.x operators operator-precedence


【解决方案1】:

python operator precedence 规则优先考虑- 运算符,然后是按位| 运算符:

现在我们有一个setunion,重载有|,还有difference,重载有-

a = set([1, 2, 3])

a|set([4])-set([2])

现在的问题变成了:为什么要适用相同的优先规则?

这是因为 python 对所有重载标准运算符的类应用相同的规则优先级来评估运算符表达式:

class Fagiolo:

    def __init__(self, val):
        self.val = val

    def __or__(self, other):
        return Fagiolo("({}+{})".format(self.val, other.val))

    def __sub__(self, other):
        return Fagiolo("({}-{})".format(self.val, other.val))

    def __str__(self):
        return self.val

red = Fagiolo("red")
white = Fagiolo("white")

new_born = red | white - Fagiolo("blue")

print(new_born)

给予:

(red+(white-blue))

【讨论】:

  • | with sets 不是按位运算符;与- 一样,它只是 一个运算符,其实际操作取决于它所使用的类型。运算符优先级由语法决定;运算符 语义 由类型确定(直到运行时才知道)。
猜你喜欢
  • 2011-07-07
  • 2013-09-30
  • 2011-06-21
  • 2013-02-24
  • 2012-08-10
  • 2020-03-05
  • 2012-12-13
相关资源
最近更新 更多