Operator precedence problem
Peter Otten
__peter__ at web.de
Sun Jun 5 03:35:44 EDT 2016
ICT Ezy wrote:
>>>> 2 ** 3 ** 2
> Answer is 512
> Why not 64?
> Order is right-left or left-right?
** is a special case:
"""
The power operator ** binds less tightly than an arithmetic or bitwise unary
operator on its right, that is, 2**-1 is 0.5.
"""
https://docs.python.org/3.5/reference/expressions.html#id21
Here's a little demo:
$ cat arithdemo.py
class A:
def __init__(self, value):
self.value = str(value)
def __add__(self, other):
return self._op(other, "+")
def __pow__(self, other):
return self._op(other, "**")
def __repr__(self):
return self.value
def _op(self, other, op):
return A("({} {} {})".format(self.value, op, other.value))
$ python3 -i arithdemo.py
>>> A(1) + A(2) + A(3)
((1 + 2) + 3)
>>> A(1) ** A(2) ** A(3)
(1 ** (2 ** 3))
More information about the Python-list
mailing list