Python:调用父类的初始化错误修复

2024-09-30 22:19:10 发布

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

我正在编写一个基本的python游戏。我正试图使它充满活力,并易于添加生物。目前我遇到了调用父类的init的问题。你知道吗

我的代码:

from main import *
class Entity:
    def __init__(self,x,y,image):
        self.x = x
        self.y = y
        self.image = image
    def changePos(self,x,y):
        self.x = x
        self.y = y
    def getPos(self):
        return self.x,self.y
    def getX(self):
        return self.x
    def getY(self):
        return self.y
    def changeImage(imagePath):
        self.image = readyImage(imagePath)
    def getImage(self):
        return self.image;
    def event(self,e):
        pass
    def onUpdate(self):
        pass

class EntityPlayer(Entity):
    def __init__(self,x,y,image):
        super(EntityPlayer,self).__init__(x,y,image)
        self.movex = 0
        self.movey = 0
    def event(self,e):
        if e.type == KEYDOWN:
            if e.key == K_LEFT:
                self.movex = -1
            elif e.key == K_RIGHT:
                self.movex = +1
            elif e.key == K_DOWN:
                self.movey = +1
            elif e.key == K_UP:
                self.movey = -1
        elif e.type == KEYUP:
            if e.key == K_LEFT or e.key == K_RIGHT or e.key == K_UP or e.key ==K_DOWN:
                movex = 0
                movey = 0
    def onUpdate(self):
        x += movex
        y += movey

错误:

Traceback (most recent call last):
  File "C:\Python27x32\prog\game\entity.py", line 1, in <module>
    from main import *
  File "C:\Python27x32\prog\game\main.py", line 43, in <module>
    startup()
  File "C:\Python27x32\prog\game\main.py", line 27, in startup
    player = entity.EntityPlayer(20,60,readyImage("ball.png"))
  File "C:\Python27x32\prog\game\entity.py", line 27, in __init__
    super(EntityPlayer).__init__(x,y,image)
TypeError: must be type, not classobj

Tags: keyimageselfgamereturninitmaindef
1条回答
网友
1楼 · 发布于 2024-09-30 22:19:10

Entity类是一个旧式类,与super()不同。如果您使Entity成为一个新的样式类,那么您的代码将正常工作。你知道吗

要使Entity成为新样式类,只需使其从object继承即可:

def Entity(object):
    def __init__(self, x, y, image):
        # ...

你的代码就可以工作了。你知道吗

有关旧样式类和新样式类的更多信息,这个StackOverflow问题有一些很好的细节:What is the difference between old style and new style classes in Python?

相关问题 更多 >