How to properly apply OOP in the bouncing ball code

Ian Kelly ian.g.kelly at gmail.com
Fri May 8 12:22:28 EDT 2015


On May 8, 2015 9:46 AM, "Tommy C" <tommyc168168 at gmail.com> wrote:
>
> I'm trying to apply OOP in this bouncing ball code in order to have
multiple balls bouncing around the screen. The objective of this code is to
create a method called settings, which controls all the settings for the
screen and the bouncing behaviour of multiple balls, under the class Ball.
However, I keep on getting errors related to attributes (e.g., speed). I'm
new to OOP in Python so your help will be much appreciated. Thanks in
advance.

As the error says, the attribute does not exist.

> class Ball:
>     def __init__(self, X, Y):
>         self.velocity = [1,1]

Here where you set it, you call it "velocity".

>         speed = self.velocity

Here you create a local variable called "speed", which you never use.

>                 if balls.ball_boundary.left < 0 or
balls.ball_boundary.right > self.width:
>                     balls.speed[0] = -balls.speed[0]

And here you look up an attribute of Ball called "speed", which doesn't
match the name you used in __init__.

This is a muddled design overall. Your Ball class represents the individual
balls bouncing around the screen. It should not also contain details about
window size and the logic for the event loop. Use a separate class for that.

Similarly, if the purpose of your settings method is to manage settings,
why does it also contain all the bouncing logic? These should probably be
separate methods.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20150508/a138a726/attachment.html>


More information about the Python-list mailing list