سؤال

class combattant(pygame.sprite.Sprite):
    def __init__(self,img,posit):
        pygame.sprite.Sprite.__init__(self)
        self.image=marche[0]
        self.image_pos=posit
        self.face=0
    def mov(self,direction):
        if direction[K_LEFT]:
            self.face=(self.face+1)%2
            self.image_pos.x -= 1
            self.image=marche[0+self.face]
            print ('gauche')
        if direction[K_RIGHT]:
            print ("droit")
            self.face=(self.face+1)%2
            self.image_pos.x += 1
            self.image=marche[2+self.face]

combattant.mov (tkey)

Here is my problem , when I run the programme containing this , I get this:

 Traceback (most recent call last):
File "F:\ISN\essai 2.py", line 63, in <module>
combattant.mov (tkey)
TypeError: mov() takes exactly 2 arguments (1 given)

Python seems to consider 'self' as argument that I need to give in order for it to work. I have tried using alpha functions or puting an empty space where the self argument is but of course I get an error saying 'Invalid Syntax' and the alpha function doesn't change anything ... Maybe I'm using this the wrong way because I'm a beginner ... It would be very helpfull if someone could help me ! Thank's in advance !

هل كانت مفيدة؟

المحلول

In your specific case, when you call combatant.move(), you are calling move on the class, not on the instance of the class. The proper way to use that method is to first create an instance.

Typically, people name their class with an uppercase letter, and their instances with a lowercase, to make problems like this easy to spot.

For example:

class Combattant(...):
    ...
combattant = Combattant(...)
combattant.move(tkey)

The reason self is required, is so that the methods know which instance they are applied to. This makes it possible to have more than once instance of the class. When you call some_instance.some_method(...), python will automatically add the self parameter when calling the method.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top