I'm trying to do some exercises from "Python crash course" by Eric Matthews. I'm pretty sure I'm following the code in the book precisely, but I'm still getting "Name not defined error" when I try to run the program:
import sys
import pygame
from settings import Settings
from ship import Ship
class AlienInvasion:
"""Class for managing game resources"""
def __init__(self):
"""initializing the game and creating resources"""
pygame.init()
self.settings = Settings()
self.scr = pygame.display.set_mode((1200, 800))
pygame.display.set_caption("Alien Invasion")
self.ship = Ship(scr)
.....
if __name__ == '__main__':
# Creating the game object and run the game
ai = AlienInvasion()
ai.run_game()
The error I get is:
Traceback (most recent call last):
File "alien_invasion.py", line 43, in <module>
ai = AlienInvasion()
File "alien_invasion.py", line 17, in __init__
self.ship = Ship(scr)
NameError: name 'scr' is not defined
If I understand correctly, program is trying to create an object of class "Ship" which is located in a separate module, but fails because it can not read the variable "scr", even though it is defined two lines above, inside of the same method.
scr
is not a local variable, but an instance variable (as you've created it with self.scr
), so you'll always have to refer to it as self.scr
You should use self.scr
instead of scr
as the variable is defined in the class as an instance variable.
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.