繁体   English   中英

Python - Class.function().function()

[英]Python - Class.function().function()

我在 codewars.com 上遇到了这个问题:First n Primes numbers。 虽然定义类 Primes() 和 Primes.first(n1) 没有问题,但我需要找到以下形式的最后一个素数:Primes.first(n1).last(n2)。 而且我不知道如何定义 last(n2) 而不会出错。

    import math
    class Primes():
       def first(self):
           primes = []
           count = 1
           prime = True
           while len(primes) != self:
               for i in range(2, int(math.sqrt(count)) + 1):
                   if count % i == 0:
                   prime = False
                   break
           if prime:
               primes.append(count)
           prime = True
           count += 1
           return primes

       def last(self):
           pass

如果我尝试 Primes.first(5).last(3) 我得到:AttributeError: 'list' object has no attribute 'last'。

...首先返回一个 list.last() 正在尝试调用列表中名为 last 的函数。 列表没有 last 调用的函数。

我想你想要这个。

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

我已经修复了您代码中的制表符。

从它的外观来看,您根本不需要最后一种方法。 如果您只想获取最后 5 个值,请使用 [-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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM