Python subclasses

I currently have a Polynomial class. Initialization is as follows:

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

I create a polynomial by creating keys by exponentials and the corresponding values ​​are coefficients. To create an instance of this class, enter the following:

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

which makes such a dictionary as follows:

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

Now I want to create a subclass of the Polynomial class called Quadratic. I want to call the constructor of the Polynomial class in the constructor of the Quadratic class, but I'm not quite sure how to do this. I tried:

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

but I get errors, who has clues? I feel like I am using the wrong parameters when I call the constructor of the Polynomial class.

+6
source share
2 answers

You probably want

 class Quadratic(Polynomial): def __init__(self, quadratic, linear, constant): Polynomial.__init__(self, (2, quadratic), (1, linear), (0, constant)) 
+10
source

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]) 
+15
source

Source: https://habr.com/ru/post/902510/


All Articles