Python 3类__init __()缺少1个必需的位置参数

时间:2018-01-16 20:25:38

标签: python arguments init

以下是代码:

class Complex:
    def __init__(self, real, imaginary):
        self.real = real
        self.imaginary = imaginary
    def __str__(self):
        return "{}+({}i)".format(self.real, self.imaginary)
    def add(self, second):
        return Complex(self.real + second.real, self.imaginary + second.imaginary)
    def subtract(self, second):
        return Complex(self.real - second.real, self.imaginary - second.imaginary)
    def multiply(self, second):
        return Complex(self.real * second.real - self.imaginary * second.imaginary, self.imaginary * second.real + \
                       self.real * second.imaginary)
    def divide(self, second):
        x = float(second.real ** 2 + second.imaginary ** 2)
        return Complex(self.real * second.real + self.imaginary * second.imaginary)/(x) + (self.imaginary * second.real - self.real * second.imaginary)/(x)

x = Complex(5,-8)
y = Complex(-1,3)


print(Complex.multiply(x,y))
print(Complex.divide(x,y))

错误是:

Traceback (most recent call last):
  File "D:/PyCharm Community Edition 2017.3.2/PyCharmProjects/lab9/venv/lab9.3.py", line 23, in <module>
    print(Complex.divide(x,y))
  File "D:/PyCharm Community Edition 2017.3.2/PyCharmProjects/lab9/venv/lab9.3.py", line 16, in divide
    return Complex(self.real * second.real + self.imaginary * second.imaginary)/(x) + (self.imaginary * second.real - self.real * second.imaginary)/(x)
TypeError: __init__() missing 1 required positional argument: 'imaginary'

所以我查看了其他类似的线程,发现了一些不仅仅是初始化方法而且还有像Complex()这样的类.division(x,y),然后它说缺少2个参数是真实的和虚构的,任何我们非常感谢有解释的想法。

1 个答案:

答案 0 :(得分:0)

您必须首先使用__init__方法所需的参数初始化您的课程,然后使用课程,调用您想要的任何方法。

x = Complex(5, -8)
y = Complex(-3, 3)
m = x.multiply(y)
d = x.divide(y)
print(m, d)

对于初始化类,其方法的第一个参数(self)会自动传递;你只需要休息。在您的情况下,剩下的唯一参数是second

<强>更新

在第二次看之后,我意识到这不是问题的根源,尽管您应该将其视为良好实践的指导原则。

要解决您的错误,只需在您Complex电话中启动的divide声明中传递另一个参数即可。你的班级目前需要两个参数而你只传递一个(密切注意缺乏昏迷)。