On 2006-12-28, jonathan.beckett <[EMAIL PROTECTED]> wrote: > Hi all, > > While working on support at work, I have been picking away at Python - > because I think it could be a valuable scripting tool for building > utilities from. I have been reading the python.org tutorials, and > playing around with some basic code, but I have ended up with a few > questions that probably have straightforward answers - any quick > explanations or assistance would be fantastic... > > > Question 1... > Given the code below, why does the count method return what it does? > How *should* you call the count method? > a = [] > a.append(1) > print a.count
a.count(1) a.count(2) > Question 2... > What is the correct way of looping through a list object in a class via > a method of it? (I've hit all sorts of errors picking away at this, and > none of the tutorials I've found so far cover it very well) - apologies > for the arbitrary class - it's the first example I thought up... > > class Gun: > Shells = 10 What you wrote created a class variable: there's only a single "Shells" object and it's shared by all instances of the class. Based on the way you're using it, I presume you want each gun to have it's own Shells value. You probably want something like this: class Gun: def __init__(self): self.Shells = 10 > class Battleship: > Gun1 = Gun() > Gun2 = Gun() > Guns = [Gun1,Gun2] > > def getShellsLeft(self): > NumShells = 0 > for aGun in Guns: > NumShells = NumShells + aGun.Shells > return NumShells > > Bizmark = Battleship() > > print Bizmark.getShellsLeft() > > > In the above code, I guess I'm just asking for the *correct* way to do > these simple kinds of things... -- Grant Edwards grante Yow! Give them at RADAR-GUIDED SKEE-BALL visi.com LANES and VELVEETA BURRITOS!! -- http://mail.python.org/mailman/listinfo/python-list