2016-06-08 18 views
0

我是一個Python語言的初學者,我面臨着在傳遞參數(如果輸入是由用戶採取)到函數中的問題python。 我正的錯誤是AttributeError的:「Complexno」對象有沒有屬性「一」如何傳遞參數(如果輸入是由用戶)到python的功能

這裏是我的代碼: 附:糾正我,如果我錯了地方(請幫助讀音字卡)

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

你通過不同ARGS調用功能,並期待在方法本身的不同。做'ob1.add(a,c,b,d)'就完成了。 –

回答

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) 
相關問題