我刚刚阅读了Think Python中关于__init__
类方法的解释。但是,我尝试启动我为 Project Euler.net 制作的 Prime Generator 函数,但仍然出现错误:
Traceback (most recent call last):
File "C:\Users\-------\Desktop\Primes.py", line 54, in <module>
Primes.__main__()
TypeError: unbound method __main__() must be called with Primes instance as first argument (got nothing instead)
我把它放在控制台中,我终于通过调用它来让它工作:
primes = Primes()
primes.primegenerator(some number)
然后它运行正常。如何让这种行为在该__init__
方法中起作用?
这是完整的代码:
class Primes():
def __init__(self, primes = []):
self.primes = primes
def primegenerator(self,limit):
'Generates primes to a given limit'
primes = [3]
i = 3 # i is the counter
while len(primes) < limit - 1:
for prime in primes:
if i % prime == 0:
i += 2
break
elif prime != primes[-1]:
continue
else:
primes.append(i)
i += 2
break
primes.insert(0,2)
return primes
def main(self):
limit = input('Enter a limit please: ')
primes = Primes.primegenerator(limit)
print '-------------------------' * 2
print The answer is: %d' %primes[-1]
print 'The sum of the primes is: %d' %sum(primes)
print print '-------------------------' * 2
这甚至是一个添加init方法 的好程序吗?