Some basic newbie questions...

Scott David Daniels scott.daniels at acm.org
Thu Dec 28 17:08:19 EST 2006


jonathan.beckett wrote:
>> ...
>>    class Battleship(object):
>>        ...
>>        def getShellsLeft(self):
>>            numShells = 0
>>            for aGun in self.guns:
>>                numShells += aGun.shells
>>            return numShells
>>        ...

> 
> Excellent example - once upon a time I used to write very neat code
> indeed, but exposure to C# had pretty much knackered that (where all
> the framework object methods are capitalized).

Here's an improvement:

For Python 2.3:  # using the "sum" primitive
     ...
     def getShellsLeft(self):
         return sum([aGun.shells for aGun in self.guns])
     ...

For Python 2.4 or later:  # allows generator expressions
     ...
     def getShellsLeft(self):
         return sum(aGun.shells for aGun in self.guns)
     ...

--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list