python子类 [英] python subclasses
问题描述
我目前有一个名为Polynomial的类,初始化如下所示:
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))
这使得字典如此:
{2: 10, 3: -4, 5: 1}
现在,我想创建一个名为Quadratic的Polynomial类的子类。我想在Quadratic类构造函数中调用Polynomial类构造函数,但是我不太清楚如何做到这一点。我试过的是:
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])
但我收到错误,有人有任何提示吗?当我调用Polynomial类构造函数时,我觉得我使用了不正确的参数。
but I get errors, anyone have any tips? I feel like I'm using incorrect parameters when I call the Polynomial class constructor.
推荐答案
你可能想要
class Quadratic(Polynomial):
def __init__(self, quadratic, linear, constant):
Polynomial.__init__(self, (2, quadratic), (1, linear), (0, constant))
这篇关于python子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!