Change operator precedence in Python

那年仲夏 提交于 2019-12-19 17:31:20

问题


I have overloaded some Python operators, arithmetic and boolean. The Python precedence rules remain in effect, which is unnatural for the overloaded operators, leading to lots of parentheses in expressions. Is there a way to "overload" Python's precedences?


回答1:


You can cheat that mechanism in this way:

  1. Override all operators to not do the calculations but create list of instructions wrapped in some object.
  2. Add your own bracket operator (ie. as a _ function).

Example:

>>> a = MyNumber(5); b = MyNumber(2); c = MyNumber(3)
>>> a + b * c
MyExpression([MyNumber(5), '+', MyNumber(2), '*', MyNumber(3)])

Brackets:

>>> a + _(b * c)

Note that _ is a function that evaluates expression (in order you enforce in it)

So if you reverse priorites you will get:

>>> _(a + b * c)
MyNumber(21)

PS. Django does similar trick with Q and F operators.




回答2:


No. It's part of the python language itself. Thats how the language parses.

Official quote: Evaluation order

Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.

Other quotes:

Python:Basics:Numbers and operators

When performing mathematical operations with mixed operators, it is important to note that Python determines which operations to perform first, based on a pre-determined precedence. This precedence follows a similar precedence to most programming languages.

Python Programming/Operators

Note that Python adheres to the PEMDAS order of operations.



来源:https://stackoverflow.com/questions/11811051/change-operator-precedence-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!