Search code examples
pythonobjectoopattributeerror

How can I use multiple files and classes in VSCode and then utilise them all in one file with the use of imports?


I am trying to make a program using OOP that is a snake replica however the beginning stages and the setup of the program is not working at all and I cannot even get the window to display properly due to constant errors occurring before then.

The errors I get are: File "c:\Users\james\OOP Snake python\world.py", line 22, in <module> Game.RunGame(Game) File "c:\Users\james\OOP Snake python\world.py", line 18, in RunGame self.window.screen.update() ^^^^^^^^^^^ AttributeError: type object 'Game' has no attribute 'window' objects.py:

import turtle 
class Snake: 
    def _init_(self): 
        self.snake_head = turtle.Turtle() 
        self.InitialiseSnake() 
    def InitialiseSnake(self): 
        self.snake_head.speed(0) 
        self.snake_head.shape("square") 
        self.snake_head.color("black") 
        self.snake_head.penup() 
        self.snake_head.goto(0, 100) 
        self.snake_head.direction = "stop" 

window.py:

import turtle 

class Window: 
    def __init__(self, width, height): 
        self.screen = turtle.Screen() 
        self.screen.title("OOP Snake") 
        self.screen.bgcolor("blue") 
        self.screen.setup(width, height) 
        self.screen.tracer(0) 

world.py (main file):

import sys 
import time 
from window import Window, turtle 
from objects import Snake 
sys.path.insert(1, 'c:/Users/james/OOP Snake python') 

HEIGHT = WIDTH = 800 

class Game: 

    def __init__(self, window, snake): 
        self.window = Window(WIDTH, HEIGHT) 
        self.snake = Snake() 

    def RunGame(self): 
        # game loop 
        while True:
            self.window.screen.update() 

Game.RunGame(Game) 

I was expecting this to load up the window however it simply just gives the errors above.


Solution

  • in the method RunGame, you should use the self attribute, instead you are using the class name (which only can access static attributes/method).

    Also you are making a recursive call (i.e. the method is calling itself which will end you up with a StackOverFlow error.

    You should simply remove this line.

    Replace

    Game.RunGame(Game)
    

    with

    game = Game()
    game.RunGame()
    

    This should solve the AttributeError problem. Basically what we did here is that we instantiated an object of the class Game so that we can call its member method.

    See this for in detail explanation.