Some basic newbie questions...

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


jonathan.beckett 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...
Work through the tutorial; don't expect simply reading it to work.

> 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
count is a method, so this is a bound method expression.
What you _mean_ is:
     a = []
     a.append(1)
     print a.count(1)  # to count the ones.

> 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
> 
> 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()
Too many misconceptions here (I changed to a more PEP-8 style naming):

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

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

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

   theBizmark = Battleship()
   print theBizmark.getShellsLeft()


> In the above code, I guess I'm just asking for the *correct* way to do
> these simple kinds of things...

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



More information about the Python-list mailing list