如何将参数(如果输入由用户获取)传递给 python 中的函数

how to pass arguments(if the input is taken by user) to functions in python

我是 Python 语言的初学者,我在将参数(如果输入由用户采用)传递给 python[=18 中的函数时遇到问题=]. 我得到的错误是 A​​ttributeError: 'Complexno' object has no attribute 'a'

这是我的代码: P.S。如果我哪里错了请纠正我(请帮助我卡住)

 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)

您正在引用一个您尚未设置的 class 变量。

如果删除方法中的 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,用实部和虚部对其进行初始化,然后将您关心的操作重载到 return 另一个复数。

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)

但是如果您要创建自己的 class,您可能想要实现比这更多的方法。

请参阅 this page 以获取要添加的方法示例,但是,该站点看起来像是为 2.7 编写的,因为它们使用 __div__ 而不是 [=28= 所需的两种除法方法].

使用此 class,您可以执行如下操作:

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)