【发布时间】: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