2015-02-06 100 views
0

我試圖做一個程序,找到一個數字是否是質數。不支持的操作數類型爲/:'實例'和'int'

文件2:

class Number(): 
    def __init__(self, x): 
     self.x = float(x) 
    def is_prime(x): 
     x = x 
     Div = 2 
     while ((x/2) > Div): 
      if(x == 2): 
       return True 
      elif(x == 3): 
       return True 
      else: 
       while((x/2) > Div): 
        if(x%Div == 0): 
         return False 
        elif(Div >= (x/2)): 
         return True 
        else: 
         Div = Div + 1 

文件1:

from File2 import * 

N = Number(10) 

print N.is_prime() 

當我運行它,我得到這個:

Traceback (most recent call last): 
File "File 1", line 5, in <module> 
print N.is_prime() 
File "File 2", line 19, in is_prime 
while ((x/2) > Div): 
TypeError: unsupported operand type(s) for /: 'instance' and 'int' 

任何人都知道如何解決這一問題?

+1

我很好奇你爲什麼做了一個包裝類的數字。只需直接使用Python的數字並編寫一個獨立函數'is_prime'。面向對象的方法在這裏是過度的。 – 2015-02-06 21:17:53

回答

1

@Daniel羅斯曼曾與類定義中涉及的語法問題。這是對你選擇的算法本身的修正,如果x是素數,並且將4標識爲質數,則它按原樣返回None(如果函數退出而沒有遇到明確的return語句,則返回該函數)。您嵌套的while循環不是必需的。嘗試:

class Number(): 
    def __init__(self, x): 
     self.x = float(x) 
    def is_prime(self): 
     x = self.x 
     if(x == 2): 
      return True 
     elif(x == 3): 
      return True 
     else: 
      Div = 2 
      while((x/2) >= Div): 
       if(x%Div == 0): 
        return False 
       else: 
        Div = Div + 1 
     return True 

for i in range(2,36): 
    N = Number(i) 
    print i, N.is_prime() 
2

你實際上試圖做self/2。參數x指向self並且因爲它是Number類的實例,所以出現此錯誤。

您需要更換x傳遞給你的方法用self.x,改變方法的簽名是:

def is_prime(self): 
    x = x # remove this 
    Div = 2 
    while ((self.x/2) > Div): 
     .... 
4

你的語法很迷茫。任何Python類中的實例方法的第一個參數始終是實例本身,通常稱爲self。僅僅因爲你稱爲參數x並不是它原來設置的實際屬性x:您將不得不參考x.x。但是,最好使用標準名稱,並引用self.x

def is_prime(self): 
    x = self.x 
相關問題