1

I am programming a basic python game. I am attempting to make it dynamic and easy to add creatures to. Currently I am running into the issue of calling the init of the parent class.

My code:

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

The Error:

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
4

1 回答 1

3

该类Entity是一个老式的类,不能像super(). 如果你创建Entity一个新的样式类,你的代码就可以工作。

要创建Entity一个新的样式类,只需让它继承自object

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

然后您的代码将起作用。

有关新旧样式类的更多信息,这个 StackOverflow 问题有一些很好的细节:Python 中旧样式和新样式类有什么区别?

于 2013-06-09T00:56:09.133 回答