python 子类

发布于 2024-12-18 07:40:42 字数 640 浏览 1 评论 0原文

我目前有一个名为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月亮是我掰弯的 2024-12-25 07:40:42

您还应该使用 super() 而不是使用直接构造函数。

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

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])
羅雙樹 2024-12-25 07:40:42

你可能想要

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

You probably want

class Quadratic(Polynomial):
    def __init__(self, quadratic, linear, constant):
        Polynomial.__init__(self, (2, quadratic), (1, linear), (0, constant))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文