Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python class--Super variable

Tags:

python

The below piece of code is giving me a error for some reason, Can someone tell me what would be the problem..

Basically, I create 2 classes Point & Circle..THe circle is trying to inherit the Point class.

Code:


class Point():

    x = 0.0
    y = 0.0

    def __init__(self, x, y):
        self.x = x
        self.y = y
        print("Point constructor")

    def ToString(self):
        return "{X:" + str(self.x) + ",Y:" + str(self.y) + "}"

class Circle(Point):
    radius = 0.0

    def __init__(self, x, y, radius):
        super(Point,self).__init__(x,y)
        self.radius = radius
        print("Circle constructor")

    def ToString(self):
        return super().ToString() + \
               ",{RADIUS=" + str(self.radius) + "}"


if __name__=='__main__':
        newpoint = Point(10,20)
        newcircle = Circle(10,20,0)

Error:

C:\Python27>python Point.py
Point constructor
Traceback (most recent call last):
  File "Point.py", line 29, in <module>
    newcircle = Circle(10,20,0)
  File "Point.py", line 18, in __init__
    super().__init__(x,y)
TypeError: super() takes at least 1 argument (0 given)
like image 374
user1050619 Avatar asked May 31 '12 17:05

user1050619


2 Answers

It looks like you already may have fixed the original error, which was caused by super().__init__(x,y) as the error message indicates, although your fix was slightly incorrect, instead of super(Point, self) from the Circle class you should use super(Circle, self).

Note that there is another place that calls super() incorrectly, inside of Circle's ToString() method:

        return super().ToString() + \
               ",{RADIUS=" + str(self.radius) + "}"

This is valid code on Python 3, but on Python 2 super() requires arguments, rewrite this as the following:

        return super(Circle, self).ToString() + \
               ",{RADIUS=" + str(self.radius) + "}"

I would also recommend getting rid of the line continuation, see the Maximum Line Length section of PEP 8 for the recommended way of fixing this.

like image 151
Andrew Clark Avatar answered Oct 04 '22 13:10

Andrew Clark


super(..) takes only new-style classes. To fix it, extend Point class from object. Like this:

class Point(object):

Also the correct way of using super(..) is like:

super(Circle,self).__init__(x,y)
like image 36
UltraInstinct Avatar answered Oct 04 '22 13:10

UltraInstinct