Search code examples
pythonpython-2.7pygameattributeerror

Why do I get an AttributeError when calling a class in a seperate module?


I'm (attempting) to recreate Mario level 1-1 in Pygame with Python 2.7.12. these are the two relevant files:

main.py: http://pastebin.com/HXmBdJ2a

mario.py: http://pastebin.com/29xu1tMM
My problem is: when I run main.py, the interpreter gives me this error message:

Traceback (most recent call last):
  File "C:/path/to/main.py", line 6, in <module>
    import mario
  File "C:\path\to\mario.py", line 7, in <module>
    import main
  File "C:\path\to\main.py", line 47, in <module>
    game = Game()
  File "C:\path\to\main.py", line 26, in __init__
    self.main_loop()
  File "C:\path\to\main.py", line 39, in main_loop
    self.Mario = mario.Mario()
AttributeError: 'module' object has no attribute 'Mario'
Process finished with exit code 1


I'm confused, as mario.py does the class Mario. If I try to run mario.py, I get this error:

Traceback (most recent call last):
  File "C:/path/to/mario.py", line 7, in <module>
    import main
  File "C:\path\to\main.py", line 6, in <module>
    import mario
  File "C:\path\to\mario.py", line 12, in <module>
    sheet = pygame.image.load("../assets/images/MarioLuigiSprites.png").convert()
pygame.error: No video mode has been set
Process finished with exit code 1


Could anyone explain this to me?
EDIT: I fixed it by adding:
import sys sys.path.insert(0, "scripts")
import mario


Solution

  • The AttributeError: 'module' object has no attribute 'Mario' in this case come from the fact that the Game class doesn't have an attribute called Mario, as you do not define it in the init of your Game class. To make it clear, you do not have:

    class Game(object):
        def __init__(self):
            self.fps = 60
            self.showfps = True
            self.clock = pygame.time.Clock()
    
            # Set FPS
            self.clock.tick(self.fps)
    
            self.Mario = mario.Mario()  # notice this line!!!
            .......
            .......
    

    Either you have self.Mario = mario.Mario() in the __init__ of Game class or call just Mario = mario.Mario() in the code you have.
    This means that keeping the code you have already you should do:

    def main_loop(self):
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.closegame()
            Mario = mario.Mario()  # notice: it's not self.Mario....
            DISPLAYSURF.fill(const.BLACK)   
    

    Side note: why do you call mario = Mario() at the end of your mario.py? Try to remove that.
    And if you do not use any methods or classes defined in main.py you can remove import main in mario.py.