On 28 Dec 2006 08:40:02 -0800, "jonathan.beckett"
<[EMAIL PROTECTED]> 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
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to