Some basic newbie questions...

Chris Mellon arkanes at gmail.com
Thu Dec 28 11:52:36 EST 2006


On 28 Dec 2006 08:40:02 -0800, jonathan.beckett
<jonathan.beckett at gmail.com> 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
>

print a.count(). There's a "Python for VB programmers" out there
somewhere, see if you can find it. In python, functions (and methods
which are special cases of functions) are first class objects, so
you're printing the function object, not calling it.

>
> 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()
>
>
> In the above code, I guess I'm just asking for the *correct* way to do
> these simple kinds of things...
>

You have the right idea but you've got your object instantiation
wrong. As I write this, I see an email from Grant Edwards that sums
things up nicely, I'll let him explain it.

I suggest working through the Python tutorial and Dive Into Python,
which will introduce you to the concepts you're getting wrong here.

> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list