[Tutor] totalViruses[i] /= float(numTrials),

Prasad, Ramit ramit.prasad at jpmorgan.com
Thu Apr 25 01:02:54 CEST 2013


Alan Gauld wrote:
> On 24/04/13 20:32, Oscar Benjamin wrote:
> > On 24 April 2013 20:07, Alan Gauld <alan.gauld at btinternet.com> wrote:
> >> On 24/04/13 16:52, Dave Angel wrote:
> >>
> >>>> Does it mean? ;  totalViruses[i] = totalViruses[i]/float(numTrials)
> >>>>
> >>> As the others have said, that's exactly right, at least if
> >>> totalViruses[i] is immutable, like an int or a float.
> >>
> >>
> >> What difference does immutability make here?
> 
> > The subtle distinction that Dave is referring to is about modifying an
> > object in place vs rebinding a name to a newly created object.
> 
> Sure, the bejhaviour with regard to the objects after the opreation is
> slightly different. But it makes noi dsifference to the duality of
> 
> x += n
> v
> x = x + n
> 
> The mutability issues are identical.
> 
> > Which behaviour occurs is entirely up to the author of the __iadd__
> > method of the class in question. This method can modify and return
> > self or it can return a different object.

Actually being able to return anything is true of even non iXXX 
methods like __div__. That's why without code, it is impossible
to say for sure, but probably it does what is expected.

>>> class Foo(object):
...     def __div__(self, num):
...         return 'shanana'*num # Bad!
...     
>>> z  = Foo()
>>> z /= 2
>>> z
'shananashanana'

> 
> This does make a difference because iadd (etc) can make a difference and
> I had forgotten that there are a separate set of operator methods for
> the ixxx operations, I was assuming that ixxx called the standard xxx.
> So in the special case of a user type implementing xxx differently to
> ixxx the behaviour might differ. But for all other cases I can think of
> the duality will still work? Apart from this exception
> 
> x += y
> 
> will yield the same result as
> 
> x = x + y
> 
> I think....

The only usecase (among built-ins) that I could find to contradict 
the statement, but I think it is a special case.

>>> a = [1,2,3] 
>>> b = (a,'c')
>>> b[0]+= [4]
TypeError: 'tuple' object does not support item assignment

>>> print b
([1, 2, 3, 4], 'c')
>>> b[0] = b[0] + [5]
TypeError: 'tuple' object does not support item assignment

>>> print b
([1, 2, 3, 4], 'c')


~Ramit


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  


More information about the Tutor mailing list