0

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

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

thanks @dano, one last question why in the class Pixel why should I put in the super a call to itself, I mean super(Pixel,..)?
super works by searching for the method you want to call in the classes listed in the __mro__ attribute of the type you pass as the first argument to super. So, if you want to find the printInfo method for Pixel, you would want to pass Pixel as the argument. You can read more about how it works here. Note that in Python 3.x, super has been enhanced so that you can simply call super().printInfo()/super().__init__(self, x, y) in this case. But since you're using Python 2.x, you have to use the longer version.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.