Object help

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Jan 11 17:20:17 EST 2009


On Sun, 11 Jan 2009 14:06:22 -0800, killsto wrote:

> I have a class called ball. The members are things like position, size,
> active. So each ball is an object.
> 
> How do I make the object without specifically saying ball1 = ball()?
> Because I don't know how many balls I want; each time it is different.
> 
> The balls are to be thrown in from the outside of the screen. I think
> you get that is enough information.
> 
> This doesn't directly pertain to balls, I have wanted to do something
> like this for many different things but didn't know how.
> 
> I would think something like:
> 
> def newball():
>      x = last_named_ball + 1
>     ball_x = ball(size, etc) # this initializes a new ball return ball_x
> 
> But then that would just name a ball ball_x, not ball_1 or ball_2.


This is the TOTALLY wrong approach.

Instead of having named balls, have a list of balls. 

balls = []  # no balls yet
balls.append(Ball())  # one ball comes in from off-screen
balls.append(Ball())  # and a second
del balls[0]  # the first ball got stuck in a tree
balls = []  # all the balls were swept up in a hurricane and lost
balls = [Ball(), Ball(), Ball(), Ball()]  # four balls come in
balls.append(Ball())  # and a fifth
for b in balls:
    print b.colour  # print the colour of each ball

and so forth.



-- 
Steven



More information about the Python-list mailing list