简体   繁体   中英

Python: calling __init__ of parent class - Error fix

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

The Entity class is an old style class, which does not work like that with super() . If you make Entity a new style class, your code will work.

To make Entity a new style class, simply make it inherit from object :

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

Your code will then work.

For more information on old vs. new style classes, this StackOverflow question has some good details: What is the difference between old style and new style classes in Python?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM