简体   繁体   中英

Python inheritance with super

I have two files each of them holding distinct classes. The code for my first class is the following:

class Point:
    def __init__(self,x,y):
        self.x=x
        self.y=y

    def getX(self):
        return self.x

    def printInfo(self):
        print self.x,",",self.y

now I have a class Pixel that inherits from Point:

from fileA import Point

class Pixel(Point):
    def __init__(self,x,y,color):
        #Point.__init__(self,x,y)     //works just fine
        super(Pixel,self).__init__()
        self.color=color

    def printInfo(self):
        super(Pixel,self).printInfo()
        print self.color

So as you can see Pixel inherits from Point, and it overrides the method printInfo. I have two problems here, first in the constructor of Pixel the line that is commented works fine, but the version with super throws an error. Also when I want to call from the printInfo method to the printInfo of the base class it throws another error. The question that I have is how can I use super in both, constructor and overrided method, so that it works?

I am using Python 2.7 and the error is TypeError: must be type, not classobj

Thanks

First, you can only use super with new-style classes, but Point is currently an old-style class. To make it a new-style class, it must inherit from object :

class Point(object):
    def __init__(self,x,y):
        self.x=x
        self.y=y

    def getX(self):
        return self.x

    def printInfo(self):
        print self.x,",",self.y

Second, you have to pass the arguments that Point.__init__ expects when you call it with super , just like you do using Point.__init__(self,...) directly:

class Pixel(Point):
    def __init__(self,x,y,color):
        super(Pixel,self).__init__(x, y)  # Don't forget x,y
        self.color=color

    def printInfo(self):
        super(Pixel,self).printInfo()
        print self.color

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