python subclasses
Asked Answered
G

2

7

I currently have a class called Polynomial, The initialization looks like this:

def __init__(self, *termpairs):
    self.termdict = dict(termpairs) 

I'm creating a polynomial by making the keys the exponents and the associated values are the coefficients. To create an instance of this class, you enter as follows:

d1 = Polynomial((5,1), (3,-4), (2,10))

which makes a dictionary like so:

{2: 10, 3: -4, 5: 1}

Now, I want to create a subclass of the Polynomial class called Quadratic. I want to call the Polynomial class constructor in the Quadratic class constructor, however im not quite sure how to do that. What I have tried is:

class Quadratic(Polynomial):
def __init__(self, quadratic, linear, constant):
    Polynomial.__init__(self, quadratic[2], linear[1], constant[0])

but I get errors, anyone have any tips? I feel like I'm using incorrect parameters when I call the Polynomial class constructor.

Gheber answered 28/11, 2011 at 0:36 Comment(0)
P
11

You probably want

class Quadratic(Polynomial):
    def __init__(self, quadratic, linear, constant):
        Polynomial.__init__(self, (2, quadratic), (1, linear), (0, constant))
Presswork answered 28/11, 2011 at 0:39 Comment(1)
Thanks this worked, I just put the numbers in the wrong place.Gheber
R
15

You should also use super() instead of using the constructor directly.

class Quadratic(Polynomial):
    def __init__(self, quadratic, linear, constant):
       super(Quadratic, self).__init__(quadratic[2], linear[1], constant[0])
Remorseless answered 28/11, 2011 at 0:43 Comment(2)
Can you elaborate on why that is better?Drislane
Got it. See this post for more info: #576669Drislane
P
11

You probably want

class Quadratic(Polynomial):
    def __init__(self, quadratic, linear, constant):
        Polynomial.__init__(self, (2, quadratic), (1, linear), (0, constant))
Presswork answered 28/11, 2011 at 0:39 Comment(1)
Thanks this worked, I just put the numbers in the wrong place.Gheber

© 2022 - 2024 — McMap. All rights reserved.