为什么Python认为类中的self是一个我必须考虑的参数

2024-10-04 03:19:21 发布

您现在位置:Python中文网/ 问答频道 /正文

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)

这是我的问题,当我运行包含这个的程序时,我得到:

 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似乎认为“self”是我需要给出的参数,以便它工作。我试过使用alpha函数,或者在自变量所在的空白处放置一个空格,但是我当然会得到一个错误,说“无效语法”,alpha函数不会改变任何东西。。。也许我用错了,因为我是初学者。。。如果有人能帮我,那就太好了!提前谢谢你!你知道吗


Tags: posimageselfifinitdefpygameface
1条回答
网友
1楼 · 发布于 2024-10-04 03:19:21

在您的特定情况下,当您调用combatant.move()时,您是在类上调用move,而不是在类的实例上调用。使用该方法的正确方法是首先创建一个实例。你知道吗

通常,人们用大写字母命名类,用小写字母命名实例,以便于发现此类问题。你知道吗

例如:

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

之所以需要self,是为了让方法知道它们应用于哪个实例。这样就可以有一个以上的类实例。调用some_instance.some_method(...)时,python将在调用方法时自动添加self参数。你知道吗

相关问题 更多 >