我刚开始使用类,我需要在类中放置一些代码。我已经让代码在课堂外按预期工作了:
minnum = 1
maxnum = 100
num = 1
points = 0
count = 9000
while num in range(minnum, (maxnum + 1)):
points += int(num + 300 * 2 * num / 3)
num += 1
if count < (points / 4):
num -= 1
break
print num #Prints "19"
count
实际上应该从0开始,但我在第一个例子中将它设置为9000(而在第二个例子中我将count
从0更改为9000)
class numbers():
def __init__(self):
self.minnum = 1
self.maxnum = 100
self.num = 1
self.points = 0
self.count = 0
def num(self):
while self.num in range(self.minnum, (self.maxnum + 1)):
self.points += int(self.num + 300 * 2 * self.num / 3)
self.num += 1
if self.count < (self.points / 4):
self.num -= 1
break
return self.num
number = numbers()
number.count = 9000
print number.num #Prints "1"
我做错了什么? (我希望print number.num
返回与第一个代码中相同的值,“19”而不是“1”)
答案 0 :(得分:3)
在第二个示例中,您没有调用num()
方法,并且您可能不希望以相同的名称(“num”)调用变量和方法!
(作为一种风格问题,我还建议您通过count
初始化程序初始化__init__
,而不是直接设置count
def __init__(self, count):
self.count = count
# etc...
number = numbers(9000)