TypeError:必须使用Player实例作为第一个参数调用未绑定方法player_init()(改为使用int实例)

时间:2016-12-25 02:54:13

标签: python typeerror

import pygame
pygame.init()

width, height = 1000, 700
window = pygame.display.set_mode((width, height))

class Player:
    def __init__(self, x, y):
        self.pos_x = x
        self.pos_y = y
        self.width, height = 1000, 700
        self.window = pygame.display.set_mode((width, height))

    def player_init(self):
        sprite = pygame.image.load("Character Sprite.png")
        self.window.blit(sprite, (self.pos_x, self.pos_y))

while 1:
    Player.player_init(500-38, 350-49)

我一直在四处寻找,但我似乎无法找到解决这种类型错误的原因

  

TypeError:必须使用player_init()实例作为第一个参数调用未绑定方法Player(而不是int实例)

每当我创建一个类时,

就会一直弹出。

3 个答案:

答案 0 :(得分:0)

您需要执行Player(x, y).player_init()因为player_init还需要self参数,该参数也使用__init__中指定的变量。您还使用2个参数调用player_init,但它只接受一个。

答案 1 :(得分:0)

首先(在while之前)创建具有预期参数的类Player的实例

player = Player(500-38, 350-49)

以后再使用它(但没有参数)

player.player_init()

但对我来说,你的代码看起来应该是这样的

import pygame

# --- constants --- (UPPER_CASE names)

WIDTH  = 1000
HEIGHT = 700

# --- classes --- (CamelCase names)

class Player:
               # <- empty line to make code more readable
    def __init__(self, x, y):
        self.image = pygame.image.load("Character Sprite.png")
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

    def draw(self, surface):
        surface.blit(self.image, self.rect)

# --- functions --- (lower_case names)

# empty

# --- main ---

# - init -

pygame.init()
window = pygame.display.set_mode((WIDTH, HEIGHT))

# - objects -

player = Player(500-38, 350-49)

# - mainloop -

while True:

    # other code

    player.draw(window)

self.rect对于设置位置非常有用,即。 self.rect.center它具有检查冲突的功能。 player.rect.collidrect(enemy.rect)player.rect.collidpoint(mouse_pos)

有用的课程pygame.spripte.Group()期望self.rectself.image自动绘制所有精灵。

答案 2 :(得分:0)

import pygame

# --- constants --- (UPPER_CASE names)

WIDTH = 1000
HEIGHT = 700

# --- classes --- (CamelCase names)

class Player:

    def __init__(self, x, y):
        self.image = pygame.image.load("Character Sprite.png")
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

    def draw(self, surface):
        surface.blit(self.image, self.rect)

# --- functions --- (lower_case names)

# empty

# --- main ---

# - init -

pygame.init()

# - objects -

player = Player(500-38, 350-49)
player.draw(pygame.display.set_mode((WIDTH, HEIGHT)))

# - mainloop -


while True:
    # other code
    pygame.display.flip() # add to out image from display