Bug or feature?

James Henderson james at logicalprogression.net
Thu Jan 15 05:25:48 EST 2004


On Thursday 15 January 2004 5:40 am, Alexey Nezhdanov wrote:
> Hello. Found a strange python behaivoir while writing some object. I've
> stripped out all other stuff so the problem is stright here:
> =================================
> #!/usr/bin/python
>
> class Object:
>      def __init__(self,val):
>          self.val=val
>
>      def Sub(self,delta):
>          self.val-=delta
>          return delta
>
> c=Object(1)
>
> ### case 1 ###
> d=c.Sub(1)
> c.val+=d
> print 'case A:',c.val
>
> ### case 2 ###
> c.val+=c.Sub(1)
> print 'case B:',c.val
> =================================
> Case 1 and case 2 prints out different calues (1 and 2 respectively).
> Do not know - if this is a bug or feature of python.
>
> --
> Alexey Nezhdanov

This is the expected behaviour.

The terms on the RHS (c.val and c.Sub(1) in case 2) are evaluated left to 
right before being added together.  If you'd reversed the terms of case 2 and 
written:

c.val = c.Sub(1) + c.val

c.val would end up as 1.

James





More information about the Python-list mailing list