python 子类
我目前有一个名为 Polynomial 的类,初始化如下所示:
def __init__(self, *termpairs):
self.termdict = dict(termpairs)
我通过将键设为指数来创建多项式, 相关值是系数。要创建此类的实例,请输入如下:
d1 = Polynomial((5,1), (3,-4), (2,10))
这会生成如下所示的字典:
{2: 10, 3: -4, 5: 1}
现在,我想创建 Polynomial 类的一个子类,称为 Quadratic。我想在二次类构造函数中调用多项式类构造函数,但是我不太确定如何做到这一点。我尝试过的是:
class Quadratic(Polynomial):
def __init__(self, quadratic, linear, constant):
Polynomial.__init__(self, quadratic[2], linear[1], constant[0])
但我收到错误,有人有任何提示吗?当我调用 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))
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您还应该使用
super()
而不是使用直接构造函数。You should also use
super()
instead of using the constructor directly.你可能想要
You probably want