[Tutor] Language truce
D-Man
dsh8290@rit.edu
Thu, 28 Jun 2001 16:08:46 -0400
On Thu, Jun 28, 2001 at 12:40:31PM -0700, Michael Powe wrote:
| >>>>> "Danny" == Danny Yoo <dyoo@hkn.eecs.berkeley.edu> writes:
|
| Danny> On Thu, 28 Jun 2001, Michael Powe wrote:
|
| >> A couple things I mentioned, like you can't increment through
| >> loops.
|
| Danny> I'm a little confused by what you mean by "incrementing
| Danny> through loops". Can you give an example of what you mean?
|
| The standard C (for i=0; i < n; i++), which uses the increment
| operator (i++) which is not present in python. I'm sure there must be
| some discussion somewhere about why the decision was made to leave
| this out, I just have not come across it.
Prior to Python 2.0 there was no augmented assignment either. There
was quite a bit of discussion on c.l.py about how to add them and
whether or not the increment/decrement operator made sense.
First I'll explain how augmented assignment works. You can define a
class such as
class Foo1 :
def __iadd__( self , other ) :
self.append( other ) # assume append is defined
return self
this does an in-place addition, like what would happen to a list. The
odd-looking 'return self' is because the interpreter assigns to the
LHS whatever was returned by the __iadd__ method. So
o = Foo1()
o += 1
print o
would show that 'o' had changed. The following shows that 'o' is
really the same object :
o = Foo1()
print id( o )
o += 1
print id( o )
This works for any type, mutable or immutable. For a tuple the
implementation would be more like :
class Foo2 :
def __iadd__( self , other ) :
return self + other # __add__ returns a new instance, BTW
so the result is 2 different objects :
o2 = Foo2()
print id( o2 )
print o2
o2 += 1
print id( o2 )
print o2
The issue with '++' and '--' is that what does it mean to "add 1" to a
list, string, tuple, or class instance? Also, not every object can be
modified in-place. The conclusion was that '++' is only syntax sugar
for the special case '+= 1', and that the implementation of augmented
assignment (briefly explained above) works nicely for both mutable and
immutable types, and all types of objects.
| Yes, as someone else points out, you can use range(), but obviously
| that is not the same thing. (In some cases, it may be functionally
| equivalent and maybe that is the point.) Also, maybe it's just me,
| but I consider
|
| k = k+1
|
| as a loop counter to just be unacceptably clumsy. Forcing me to use
| that construct tells me that I should not be designing my program that
| way.
It is just a different spelling of the same operation and this
argument apparently has more aesthetic content than technical content.
-D