Search code examples
pythonattributeerror

Python class attributeError, even though I have that attribute


I'm making some code with pygame and for some twisted, wicked reason I get an attributeError when obviosly I have that atrribute. What is even more interesting that I only get error at the second if statement. If I comment it out I get no errors. It is very annoying. Somebody please help me out!

The vector() object I used is a pygame.math.Vector2 object

class Player:
    def __init__(self, pos) -> None:
        self.surf = self.player_surf()
        self.pos = vector(pos[0],pos[1]-self.surf.get_height())
        self.vel = vector(0,0)
        self.rect = self.surf.get_rect(midbottom=self.pos)
    
    def player_surf(self):
        self.orient = 'Right'
        surf = pygame.image.load('assets\player\player.png').convert_alpha()

        if self.orient == 'Left' and self.vel.x > 0:
            self.orient = 'Right'
            surf = pygame.transform.flip(surf, True, False).convert_alpha()
        elif self.orient == 'Right' and self.vel.x < 0:
            self.orient = 'Left'
            surf = pygame.transform.flip(surf, True, False).convert_alpha()
        return surf

The error message:

Traceback (most recent call last):
  File "d:\Python_projects\Gyakorlások\platformer\main.py", line 84, in <module>
    game = main()
  File "d:\Python_projects\Gyakorlások\platformer\main.py", line 26, in __init__
    self.player = Player(vector(WIN_WIDTH//2, self.ground))
  File "d:\Python_projects\Gyakorlások\platformer\main.py", line 54, in __init__
    self.surf = self.player_surf()
  File "d:\Python_projects\Gyakorlások\platformer\main.py", line 66, in player_surf
    elif self.orient == 'Right' and self.vel.x < 0:
AttributeError: type object 'Player' has no attribute 'vel'

Solution

  • Attributes in Python are created dynamically when __init__ gives them a value, not statically at compile time. You are calling the player_surf method before you define self.vel but try to use self.vel in the body of player_surf. If you rearrange the order of the lines in __init__ so that you define vel before (indirectly) trying to use it, that error will go away.