Frage

I've just read the explanation in Think Python about __init__ methods for classes. However, I tried to initiate a Prime Generator function I made for Project Euler.net and I continued to get the error:

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)

I pulled it up in a console, and I finally got it to work by calling this:

primes = Primes()
primes.primegenerator(some number)

It then ran properly. How do I get this behavior to work in the __init__ method?

Here is the full code:

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   

Would this even be a good program to add an init method to?

War es hilfreich?

Lösung

The error is in Primes.__main__() - you need to pass an instance like Primes.__main__(self) or Primes.__main__(primes)

but for a full answer you would have to show the full code.

It is not a good idea to do

Primes = Primes()

before that statement, Primes is a class (or maybe a function), afterwards it is an instance. Better say

primes = Primes()

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top