正在阅读Python教程并且已经问过related question here(我之前的示例中的代码并感谢@emmanuel)
代码:
import math, time
class PrimeFactor:
def __init__(self):
pass
def isprime(self,number):
start=time.clock()
fnum = [1,]
print "Reticulating Splines..."
last = int(math.ceil(math.sqrt(number)))
for p in range(2, last + 1):
if (number % p) == 0:
fnum.append(p)
fnum.append(number / p)
# Remove duplicates, sort list
fnum = list(set(fnum))
fnum.sort()
end=time.clock()
if len(fnum) > 1:
return number, "is not a prime because of these factors", fnum ,"Time taken", end-start
else:
return True, "Time taken", end-start
print "Prime or factor calculator v3 using sqrt(n)"
print #
num =int(raw_input("Enter number: "))
eg=PrimeFactor()
print eg.isprime(num)
从这段代码中,我试图得到变量fnum,它是函数(方法)isprime的本地变量,它包含因子列表。通过调用
访问它print eg.isprime(num).fnum
给了我一个错误
AttributeError: 'tuple' object has no attribute 'fnum'
我想我不能这样调用局部变量。
此外,代码不可重复使用。所以我决定进行重写,使其更加模块化。
重写代码:
import math
class PrimeFactor:
def __init__(self):
pass
def isPrime(self,number):
fnum = [1,]
last = int(math.ceil(math.sqrt(number)))
for p in range(2, last + 1):
if (number % p) == 0:
return False
else:
return True
def getFactors(self,number):
fnum = [1,]
last = int(math.ceil(math.sqrt(number)))
for p in range(2, last + 1):
if (number % p) == 0:
fnum.append(p)
fnum.append(number / p)
# Remove duplicates, sort list
fnum = list(set(fnum))
fnum.sort()
if len(fnum) > 1:
return fnum
else:
return None
num =int(raw_input("Enter number: "))
eg=PrimeFactor()
if eg.isPrime(num):
print num, "is a Prime Number"
else:
print num, "is not a prime number"
print "Factors", eg.getFactors(num)
我不得不放弃时间计算。我可以在使用实例时计算时间。
问题:
我可以在上一个示例中访问本地变量fnum
吗?如果是,怎么样?(我猜不是)。如果不是,那么重写代码是否足够好还是我做错了?
答案 0 :(得分:3)
你需要:
print eg.isprime(num)[2]
(你的方法是返回一个元组,你需要第三个成员,这就是全部)
答案 1 :(得分:3)
您修改的问题在于您复制了微积分。我理解你只想获得计算的因子,这只涉及创建fnum作为属性:
import math, time
class PrimeFactor:
def __init__(self):
self.fnum = [1,]
self.elapsedTime = 0
def getElapsedTime(self):
return self.elapsedTime
def getFactors(self):
return self.fnum
def isprime(self,number):
start=time.clock()
self.fnum = [1,]
last = int(math.ceil(math.sqrt(number)))
for p in range(2, last + 1):
if (number % p) == 0:
self.fnum.append(p)
self.fnum.append(number / p)
# Remove duplicates, sort list
self.fnum = list(set(self.fnum))
self.fnum.sort()
end=time.clock()
self.elapsedTime = end-start
return (not len(self.fnum) > 1 )
num =int(raw_input("Enter number: "))
eg=PrimeFactor()
if eg.isprime(num):
print num, "is a Prime Number", eg.isprime(num)
else:
print num, "is not a prime number"
print "Factors", eg.getFactors()
print eg.getElapsedTime()
您甚至可以更多地开发代码并利用之前计算的因子,从而使用动态编程。
希望这有帮助。
答案 2 :(得分:2)
无法从该函数外部访问函数的局部变量。您需要通过返回它们,或者将它们的值写入调用者可用的容器中,明确地将它们提供给调用者。