Function inside class not working in Python

Question:

I’m making a basic Pygame platformer. So I used a player class and inside it had a function called jump_action. I expected it to, you know, run the code in the function, but it says I have given an argument when the function takes none. Here’s my code:

class Player:
          def __init__(self, player_info_here):
                    self.player_info = player_info_here
          def jump_action():
                    #...jump stuff here...
                    print("Jump")

while True:
          player = Player("player info")
          #if the player is pressing space and the player is on the ground then...
          player.jump_action()

Here’s the error message:

TypeError: jump_action() takes 0 positional arguments but 1 was given
Asked By: ItleBittle

||

Answers:

add self arg to all functions that you want act as methods on this class Player:

  def __init__(self, player_info_here):
            self.player_info = player_info_here
  def jump_action(self):
            #...jump stuff here...
            print("Jump")

Edit :

in your case you create functions that will work in this way

Player.jump_action()
Answered By: Lior Tabachnik
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.