back with more issues

Steven D'Aprano steve at pearwood.info
Tue Aug 13 02:22:53 EDT 2013


On Mon, 12 Aug 2013 20:13:31 -0700, Kris Mesenbrink wrote:

> the Classes and __init__ still don't make much sense actually. i have
> tried and tried again to make it generate numbers between 0 and 5 in a
> while statement but it just doesn't seem to be working.

Hi Kris,

You might also find that the tutor mailing list is a better match for
your status as a complete beginner to Python. You can subscribe to it
here:

http://mail.python.org/mailman/listinfo/tutor


If you do, please take my advice and use individual emails, not daily
digests. It is MUCH easier to carry on a back-and-forth conversation with
individual emails.


But for now, you seem to have misunderstood what your code is doing. 
Let's start with the basics:

The method __init__ is automatically called by Python when you create a 
new instance. You almost never need to call it by hand, so 99% of the 
time, if you're writing something like "Player.__init__",  you're 
probably making a mistake.

But when you do want to call a method -- and remember, you're not 
manually calling __init__ -- you need to put round brackets (parentheses 
for Americans) after the method name. So you would say something like:

Player.__init__(arguments go inside here)

rather than just Player.__init__. Without the parentheses, you're just 
referring to the method, not actually calling it. And without the right 
number and type of arguments, you'll get an error.


So how do you create a new Player? Easy -- you just call the *class*, as 
if it were a function:

fred = Player()
barney = Player()
wilma = Player()
betty = Player()

Take note of the round brackets. If you leave them out, each of fred, 
barney, wilma, betty will be aliases to the Player class, rather than 
separate players.

So that's the first thing. Now, another potential problem. Your class 
starts off like this:

class Player():
    hp = 10
    ...more code follows


What this does is set a class-wide attribute called "hp", which every 
instance shares. Does this matter? Maybe not, it depends on how you use 
it. Your sample code doesn't show enough to tell if it will be a problem 
or not.

Next, you write this:


> while Player.hp == 10:
>     print (Player.__init__)

but since nothing in the loop changes the value of Player.hp, this will 
loop forever, or until you interrupt it. So I'm not really sure what you 
actually intend to do.

My guess is that what you actually want is something like this:


for i in range(10):
    player = Player()
    print("Player", i, "has value", player.attr)


This ought to get you started.


-- 
Steven



More information about the Python-list mailing list