在Python中更改运算符优先级 [英] Change operator precedence in Python

查看:318
本文介绍了在Python中更改运算符优先级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经重载了一些Python运算符,算术和布尔值. Python优先规则仍然有效,这对于重载的运算符而言是不自然的,从而导致表达式中包含大量括号.有没有一种方法可以超载" Python的优先级?

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?

推荐答案

您可以通过以下方式欺骗该机制:

You can cheat that mechanism in this way:

  1. 重写所有运算符,使其不执行计算,而是创建包装在某些对象中的指令列表.
  2. 添加您自己的方括号运算符(即作为_函数).
  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).

示例:

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

括号:

>>> 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使用QF运算符进行了类似的操作.

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

这篇关于在Python中更改运算符优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆