user7737008
user7737008

Reputation: 23

Python, confused by dot notation

I'm currently reading Python Crash Course, and there is that code:

import pygame


class Ship():


    def __init__(self, screen):

        """Initialize the ship, and set its starting position."""

        self.screen = screen



        # Load the ship image, and get its rect.

        self.image = pygame.image.load('images/ship.bmp')

        self.rect = self.image.get_rect()

        self.screen_rect = screen.get_rect()


        # Start each new ship at the bottom center of the screen.

        self.rect.centerx = self.screen_rect.centerx

        self.rect.bottom = self.screen_rect.bottom

I'm pretty sure i'm asking basic stuff, but nor my brain, nor my google skills aren't that good.

  1. This thing: self.rect = self.image.get_rect(). Aren't get_rect() part of pygame.Screen module? If so, shouldn't it be used like pygame.Screen.get_rect()?

  2. self.rect.centerx = self.screen_rect.centerx Too.many.dots. Is rect class instance, that is being created by get_rect() method, and centerx is attribute of that instance? Also, screen variable (or class instance?) is defined like that: screen = pygame.display.set_mode((1200, 800))

Thanks in advance!

Edit: Thanks for answers!

Upvotes: 0

Views: 227

Answers (2)

Lie Ryan
Lie Ryan

Reputation: 64913

get_rect() is a method of Surface. Both Screen and Image are a Surface (they implement the Surface interface). Screen is just special Surface that refers to the Surface that's actually mapped to a location on-screen, while other Surfaces like Image are off-screen object in the memory that can be drawn or drawn into without affecting what's on the screen.

self.rect is a Rect instance, which is used by pygame to track the position and dimension of Surface/s.

Upvotes: 0

meyer9
meyer9

Reputation: 1140

  1. In PyGame, the get_rect() function is defined in a class that represents some sort of surface. In this case, both the screen and the image have that method because both subclass surfaces and so they both have the get_rect() method.

  2. This code: self.rect.centerx = self.screen_rect.centerx can be translated as setting the centerx of the rect of myself to the centerx of the screen of myself. In other words, it moves the object to the center of the screen. The self keyword represents the current object and each dot represents a property of that object.

Upvotes: 2

Related Questions