【问题标题】:TypeError: object of type 'Fraction' has no len()TypeError:“分数”类型的对象没有 len()
【发布时间】:2020-03-01 00:04:27
【问题描述】:

我已对其进行了调整以将 self 添加到更新中,但现在我在测试内容时遇到了问题。

from file import Fraction
import random
def main():
    a = Fraction()
    b = a.update()
main()

我正在尝试使这个 for 循环工作,它应该将列表的第一个数字减去第二个,第二个减去第三个等,并使用这些值创建一个新列表。 __init__ 部分有效,但更新功能是我遇到麻烦的地方。

class Fraction():
    def __init__(self):
        shape = int(input("How many sides does the shape have? : "))
        if shape <= 0: #doesnt work with negatives?
            print("Please make a valid choice (positive integers only)")
            shape = int(input("How many sides does the shape have? : "))
        numbers = 0
        print("Your numbers are: ")
        numbers = []
        for i in range(0,shape):
            n = random.randint(1,100)
            numbers.append(n)
        print(numbers)

    def update(numbers):
        long=len(numbers)
        for i in range(long):
            newnum = numbers[i]-numbers[i+1]

        print(newnum)

【问题讨论】:

  • 方法需要一个self 参数,就像__init__ 一样。所以它应该是def update(self, numbers):,或者如果它不需要自我,就让它成为staticmethod
  • 你怎么打电话给update?它的第一个参数应该是self,那么想必你还需要传入一个数字列表。
  • 在课外使用input()很好。这样,您可以使用来自文件或数据库或硬编码列表的值运行类。它有助于一次又一次地测试具有相同值的代码。
  • 您应该使用self.numbers 来访问所有方法中的相同值。
  • 要创建新列表,您必须在for-loop 之前创建空列表并在for-loop 中使用newlist.append(newnum)。使用newnum = ... 无法创建列表,但只能获取最后一个值。

标签: python python-3.x list for-loop


【解决方案1】:

您必须使用self.number 才能访问update 中的号码。你应该在def update(number)中使用self而不是number

此外,要创建新列表,您必须在 for-loop 和 append(newnum) 之前创建空列表到此列表。之后你可以return这个列表获取它为b = ...

class Fraction():

    def __init__(self):
        shape = int(input("How many sides does the shape have? : "))

        if shape <= 0: #doesnt work with negatives?
            print("Please make a valid choice (positive integers only)")
            shape = int(input("How many sides does the shape have? : "))

        self.numbers = []
        for i in range(shape):
            n = random.randint(1, 100)
            self.numbers.append(n)
        print("Your numbers are:", self.numbers)

    def update(self):
        newlist = []

        long = len(self.numbers)
        for i in range(long-1): # it has to be long-1 because later `long-1+1`will give `long` 
            newnum = self.numbers[i] - self.numbers[i+1]
            newlist.append(newnum)

        return newlist

import random

def main():
    a = Fraction()
    b = a.update()
    print(b)
main()

顺便说一句:最好在类外使用input() 并将其作为Fraction(shape) 运行,这样它就可以使用input() 或文件或硬编码变量中的值运行。使用相同的值一次又一次地测试代码是有帮助的。

【讨论】:

  • 效果很好!您将如何得到它以便从第一个数字中减去最后一个数字?
  • self.numbers[0] - self.numbers[-1] 或者您可能需要先从最后一个减去 self.numbers[-1] - self.numbers[0]
猜你喜欢
  • 1970-01-01
  • 2015-08-21
  • 2019-05-23
  • 2013-04-18
  • 2015-01-21
  • 2021-12-19
  • 2018-08-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多