Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python subclasses

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.

like image 703
me45 Avatar asked Nov 28 '11 00:11

me45


People also ask

What are subclasses in Python?

A class which inherits from a superclass is called a subclass, also called heir class or child class.

What is the purpose of subclasses in Python?

In inheritance, a class (usually called superclass) is inherited by another class (usually called subclass). The subclass adds some attributes to superclass. Below is a sample Python program to show how inheritance is implemented in Python. # Base or Super class.

How do you access subclasses in Python?

You can just use the class directly, and you probably should. If you do have a string representing the name of a class and you want to find that class's subclasses, then there are two steps: find the class given its name, and then find the subclasses with __subclasses__ as above.

Can you make subclasses in Python?

The process of creating a subclass of a class is called inheritance. All the attributes and methods of superclass are inherited by its subclass also. This means that an object of a subclass can access all the attributes and methods of the superclass.


2 Answers

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])
like image 172
John Doe Avatar answered Sep 30 '22 17:09

John Doe


You probably want

class Quadratic(Polynomial):
    def __init__(self, quadratic, linear, constant):
        Polynomial.__init__(self, (2, quadratic), (1, linear), (0, constant))
like image 32
Cito Avatar answered Sep 30 '22 17:09

Cito