Book
Module 7 - Section 1 - Classes
Module 7 - Section 1 - Classes
Completion requirements
View
After the completion of this module the students will be able to:
- identify a class inside Python code
- present the necessary parts for constructing a class
- create code to construct a simple class
- create and use methods in a class
- distinguish the references from the objects of a class
- rewrite the classes code to implement constructors
7.1.4 - A Ball class
This example code could be used in Python/Pygame to draw a ball. Having all the parameters contained in a class makes data management easier.
class Ball():
def __init__(self):
# --- Class Attributes ---
# Ball position
self.x = 0
self.y = 0
# Ball's vector
self.change_x = 0
self.change_y = 0
# Ball size
self.size = 10
# Ball color
self.color = [255,255,255]
# --- Class Methods ---
def move(self):
self.x += self.change_x
self.y += self.change_y
def draw(self, screen):
pygame.draw.circle(screen, self.color, [self.x, self.y], self.size )
theBall = Ball()
theBall.x = 100
theBall.y = 100
theBall.change_x = 2
theBall.change_y = 1
theBall.color = [255,0,0]
This code would go inside the main loop to move and draw the ball:
theBall.move()
theBall.draw(screen)
The complete code can be downloaded from here