简体   繁体   中英

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!

  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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM