Some basic newbie questions...

Daniel Klein danielkleinad at gmail.com
Fri Dec 29 10:33:25 EST 2006


On 28 Dec 2006 08:40:02 -0800, "jonathan.beckett"
<jonathan.beckett at gmail.com> wrote:

>Hi all,
>
>Question 2...
>What is the correct way of looping through a list object in a class via
>a method of it? 

Without peeking at any of the other responses, here is what I came up
with. I hope it helps...

class Gun(object):
    def __init__(self, shells = 10):
        self.shells = shells

class Battleship(object):
    def __init__(self, shipname = '', guns = []):
        self.shipname = shipname
        self.guns = guns

    def getShellsLeft(self):
        numShells = 0
        for gun in self.guns:
            numShells += gun.shells
        return numShells            

if __name__ == '__main__':
    aShip = Battleship(shipname = "Bizmark", guns = [Gun(), Gun(6)])
    print "%s has %d shells left." \
          % (aShip.shipname, aShip.getShellsLeft())


Dan



More information about the Python-list mailing list