Menu
CoddyTech

Self Is the Object

Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 12 of 36.

One class can make as many objects as you like, and each keeps its own attributes. Give __init__ a speed parameter and two stars can fall at different speeds:

slow = Star(200, 0, 1)
fast = Star(440, 0, 3)

When you write slow.update(), Python runs Star.update(slow): self is slow, so self.y += self.speed moves slow by 1. fast.update() runs the same lines with self set to fast, and moves it by 3. One method, two objects, and neither touches the other's numbers.

That is why every value an object owns needs self. in front. A name without it, such as speed, is a plain local variable of the method: it disappears when the method ends.

challenge icon

Challenge

Easy
  1. Give __init__ a third parameter, speed, and store it as self.speed.
  2. Replace star with two stars: slow = Star(200, 0, 1) and fast = Star(440, 0, 3).
  3. Update and draw both stars every frame.

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Falling Star")
clock = pygame.time.Clock()

class Star:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.speed = 2

    def update(self):
        self.y += self.speed
        if self.y > 480:
            self.y = 0

    def draw(self, screen):
        pygame.draw.circle(screen, (255, 255, 255), (self.x, self.y), 4)


star = Star(320, 0)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    star.update()

    screen.fill((20, 22, 40))
    star.draw(screen)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Sprites and Images

Practice on your own: Pygame playground