0

So I am utterly confused as to why my Player class method is not working.

Here's part of my Player class:

class Player( pygame.sprite.Sprite ):
    def __init__( self ):

        super( Player, self ).__init__()
        self.size = self.w,self.h = 75,75
        self.image = pygame.Surface( ( self.size ) )
        self.image.fill( white )

        self.move_y = 0
        self.move_x = 0

        self.level = None

        def set_properties(self):

            self.rect = self.image.get_rect()

            self.speed = 5

        def set_position( self, x, y ):
            self.rect.x = x
            self.rect.y = y

Here is where I call the method, set_position.

player = Player()
player.set_position( 40, 40 )

Everything seems fine, but I get the following error message:

Traceback (most recent call last):
  File "C:/Desktop/CubeRunner/main_v2.py", line 194, in <module>
    player.set_position( 40, 40 )
AttributeError: 'Player' object has no attribute 'set_position'
abhi
  • 1,760
  • 1
  • 24
  • 40
  • 2
    Based on your indention, you're defining your methods in your init method. Unindent them so they're the same level as your init method and you should be okay. Also, make sure you indent the init method under the class declaration. Right now it doesn't belong to the class. – Maurice Reeves Jun 05 '16 at 17:20

1 Answers1

2

As Maurice said, your problem is with your indentation. Python is very strict about indentation in code, since it is so essential. Indentation replaces curly braces, semi-colons, etc.

Here is your code with the proper indentation:

class Player( pygame.sprite.Sprite ):
    def __init__( self ):

        super( Player, self ).__init__()
        self.size = self.w,self.h = 75,75
        self.image = pygame.Surface( ( self.size ) )
        self.image.fill( white )

        self.move_y = 0
        self.move_x = 0

        self.level = None

    def set_properties(self):

        self.rect = self.image.get_rect()

        self.speed = 5

    def set_position( self, x, y ):
        self.rect.x = x
        self.rect.y = y

If you would like some more information about indentation in Python (and why it is that way) check out these answers:

Community
  • 1
  • 1
abhi
  • 1,760
  • 1
  • 24
  • 40
  • Haha. Careless mistakes like these make me want to laugh. Thanks for spotting that out. I come from a Java background so I sometimes forget about these things xD – Derek Zhang Jun 05 '16 at 20:10
  • Haha not a problem - it happens to me all the time as well :) Hope your project turns out great! – abhi Jun 05 '16 at 20:40