我正在尝试编写一个程序来判断一个数是否为质数。
文件 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'
有人知道如何解决这个问题吗?
请您参考如下方法:
你的语法很困惑。任何 Python 类中实例方法的第一个参数始终是实例本身,通常称为 self。仅仅因为您调用了参数 x 并不能使它成为您最初设置的实际属性 x:您必须引用 x.x。但最好使用标准名称,并引用 self.x:
def is_prime(self):
x = self.x
