Python – Class.function().function()

… first returns a list.last() is trying to call a function named last on a list. A list does not have a function called last.

I think you want this.

class Primes(list):
    def first(self, amount):
        count = 1
        while len(self) < amount:
            prime = True
            for i in range(2, int(math.sqrt(count)) + 1):
                if count % i == 0:
                    prime = False
                    break
            if prime:
                self.append(count)
            count += 1
        return self # Note: self is Primes object which has a last method.

    def last(self, amount):
        ...
        return self

p = Primes()
p.first(5)
p.last(3)
# same as p = Primes().first(5).last(3) because it returns self
# Primes now inherits from list, so it works like a list but has a last method

I’ve fixed the tabbing in your code.

From the looks of it you don’t need a last method at all. If you just want to get the last 5 values use [-5:].

# Your old way edited
class Primes():
    @staticmethod
    def first(amount):
       primes = []
       count = 1
       while len(primes) < amount:
            prime = True
            for i in range(2, int(math.sqrt(count)) + 1):
                if count % i == 0:
                    prime = False
                    break
            if prime:
                primes.append(count)
            count += 1
       return primes

p = Primes.first(20)
print(p)
print(p[-5:]) # This will give you the last 5

Leave a Comment