Path: csiph.com!fu-berlin.de!uni-berlin.de!not-for-mail From: Peter Otten <__peter__@web.de> Newsgroups: comp.lang.python Subject: Re: Operator precedence problem Date: Sun, 05 Jun 2016 09:35:44 +0200 Organization: None Lines: 36 Message-ID: References: <816c651a-d0ae-4e23-a5b2-72a8f7398468@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset="ISO-8859-1" Content-Transfer-Encoding: 7Bit X-Trace: news.uni-berlin.de 9mRqS9NkmiGOw0N61YxvUADQOmMXZQ+2x5oI7EGACXvA== Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.003 X-Spam-Evidence: '*H*': 0.99; '*S*': 0.00; 'operator': 0.03; '"""': 0.05; 'python3': 0.05; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'def': 0.13; 'bitwise': 0.16; 'received:80.91.229.3': 0.16; 'received:dip0.t-ipconnect.de': 0.16; 'received:io': 0.16; 'received:plane.gmane.org': 0.16; 'received:psf.io': 0.16; 'received:t-ipconnect.de': 0.16; 'unary': 0.16; 'wrote:': 0.16; 'skip:{ 20': 0.18; '>>>': 0.20; 'subject:problem': 0.22; 'header:User-Agent:1': 0.26; 'header:X -Complaints-To:1': 0.26; 'arithmetic': 0.29; 'cat': 0.29; 'other,': 0.29; 'skip:_ 10': 0.32; 'class': 0.33; 'url:python': 0.33; 'url:org': 0.36; 'to:addr:python-list': 0.36; 'subject:: ': 0.37; 'received:org': 0.37; 'why': 0.39; 'to:addr:python.org': 0.40; 'received:de': 0.40; 'url:3': 0.60; 'power': 0.72; 'special': 0.73; '3))': 0.84; '512': 0.84; 'ict': 0.84; 'self.value': 0.84; 'url:reference': 0.91 X-Injected-Via-Gmane: http://gmane.org/ X-Gmane-NNTP-Posting-Host: p57bd9cdd.dip0.t-ipconnect.de User-Agent: KNode/4.13.3 X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.22 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-Mailman-Original-Message-ID: X-Mailman-Original-References: <816c651a-d0ae-4e23-a5b2-72a8f7398468@googlegroups.com> Xref: csiph.com comp.lang.python:109502 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))