python - 类型错误 : movement() missing 1 required positional argument: 'self'

标签 python self

我不知道该怎么做,我用谷歌搜索并查看了其他答案,但我尝试的任何方法都不起作用,我试图创建一个 Sprite ,然后移动它,我能够让 Sprite 移动,但它会立即移动回到起始位置。在 inti 这个类之后我得到 NameError: name 'image' is not Define

import pygame
import os
import sys

pygame.init()
screen = pygame.display.set_mode((448, 576))
done = False

y = 320
x = 216

clock = pygame.time.Clock()
PACMANSPRITE = pygame.image.load("pacman.png").convert_alpha()

class pacman(pygame.sprite.Sprite):
    def __init__(self, image, x, y):
        self.image = image
        self.y=y
        self.x=x
        screen.blit((image), (x,y))


    def movement(self):
        pressed= pygame.key.get_pressed()
        if pressed[pygame.K_UP]:
            self.y=y-10
        if pressed[pygame.K_DOWN]:
            self.y=y+10
        if pressed[pygame.K_LEFT]:
            self.x=x-10
        if pressed[pygame.K_RIGHT]:
            self.x=x+10
        screen.blit(image, (x,y))

while not done:
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        done = True
                        pygame.quit()
                        sys.exit()

        screen.fill((0, 0, 0))


        pacman(PACMANSPRITE, x ,y)
        pacman.movement()



        pygame.display.flip()
        clock.tick(60)

最佳答案

您直接在类上调用了该方法:

pacman.movement()

也许您想存储在该调用之前的行中创建的实例?

sprite = pacman(PACMANSPRITE, x ,y)
sprite.movement()

您可能想在循环之外创建一个实例:

sprite = pacman(PACMANSPRITE, x ,y)
while not done:
    # ...
    sprite.movement()

接下来,您的 movement 方法引用未定义的全局 image 变量;大概您指的是实例上的 image 属性,可通过 self.image 引用:

def movement(self):
    # ...
    screen.blit(self.image, (x,y))

关于python - 类型错误 : movement() missing 1 required positional argument: 'self' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45660548/

相关文章:

python - 使用 self vs cls 访问单元测试中的变量

ios - 丢失当前打开的 View 的引用

module - 在模块中存储单个函数

python - Hyperledger Indy 节点配置错误导致错误,并显示一条消息: "undefined symbol: indy_crypto_init_logger"

Python - 使用 Pytesseract 读取图像中的数字

python - pandas 数据框的处理

python - 示例 : how do I make bokeh omit missing dates when using datetime as x-axis

ruby - 为什么我不能改变 self 的值(value)?

python - 在类方法中返回 self - 这是好方法吗?

python - 通过聚合列表构建数据框