Python:调用父类的__init__ - 错误修复

时间:2013-06-09 00:49:48

标签: 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

1 个答案:

答案 0 :(得分:3)

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?