我是Python语言的初学者,我在将参数(如果输入由用户提交)传递给 python 中的函数时遇到问题。 我得到的错误是 AttributeError:' Complexno'对象没有属性' a'
这是我的代码: 附:如果我在某处错了,请纠正我(请帮助我卡住)
class Complexno:
def add(self,a,c ,b,d):
sum1=self.a+self.c
sum2=self.b+self.d
print(sum1+" + "+sum2)
def sub(self,a,c,b,d):
sub1=self.a-self.c
sub2=self.b-self.d
print(sub1+" - "+sub2)
def mul(self,a,b,c,d):
mul1=self.a*self.c
mul2=self.b*self.c
print(mul1+" * "+mul2)
def div(self,a,b,c,d):
div1=self.a/self.c
div2=self.b/self.d
print(div1+" / "+div2)
a=float(input("Enter the real part of first no"))
b=float(input("Enter the imaginary part of first no"))
c=float(input("Enter the real part of second no"))
d=float(input("Enter the imaginary part of second no"))
ob1=Complexno()
ob1.add(a,b,c,d)
ob1.sub(a,b,c,d)
ob1.div(a,b,c,d)
ob1.mul(a,b,c,d)
答案 0 :(得分:0)
您正在引用尚未设置的类变量。
如果删除方法中的self
引用,则不会再出现此问题。
class Complexno:
def add(self,a,c ,b,d):
sum1= a + c
sum2= b + d
print(sum1+" + "+sum2)
def sub(self,a,c,b,d):
sub1= a - c
sub2= b - d
print(sub1+" - "+sub2)
def mul(self,a,b,c,d):
mul1= a * c
mul2= b * c
print(mul1+" * "+mul2)
def div(self,a,b,c,d):
div1= a / c
div2= b / d
print(div1+" / "+div2)
更好的解决方案可能是创建一个复数类,使用实部和虚部初始化它,然后重载您关心的操作以返回另一个复数。
class Complexno:
def __inti__(self, real, imaginary):
self.a = real
self.b = imaginary
def __str__(self):
return "{}+{}i".format(self.a, self.b)
def __add__(self, other):
real = self.a + other.a
imaginary = self.b + other.b
return Complexno(real, imaginary)
def __sub__(self, other):
real = self.a - other.a
imaginary = self.b - other.b
return Complexno(real, imaginary)
def __mul__(self, other):
real = self.a * other.a
imaginary = self.b * other.b
return Complexno(real, imaginary)
def __floordiv__(self, other):
real = self.a // other.a
imaginary = self.b // other.b
return Complexno(real, imaginary)
def __truediv__(self, other):
real = self.a / other.a
imaginary = self.b / other.b
return Complexno(real, imaginary)
但是如果你要创建自己的类,你可能想要实现更多的方法。
有关要添加的方法的示例,请参阅this page,但是,看起来该网站是针对2.7编写的,因为它们使用__div__
而不是3.x所需的两种划分方法。
使用此类,您可以执行以下操作:
a = float(input("Enter the real part of first no"))
b = float(input("Enter the imaginary part of first no"))
c = float(input("Enter the real part of second no"))
d = float(input("Enter the imaginary part of second no"))
num1 = Complexno(a, b)
num2 = Complexno(c, d)
print(num1 + num2)
print(num1 - num2)
print(num1 * num2)
print(num1 / num2)