为什么我不能增加实例变量?

问题描述 投票:0回答:2

我想在初始化后增加

self.next
。这样,如果
var.next = 5
并且我做了
var.incr
,那么
var.next = 6

class node:
    def __init__(self, dataStored, nextNode):
        self.data = dataStored
        self.next = int(nextNode)
        self.display = (dataStored, nextNode)

    def incr(self):
        if self.next == -1:
            pass
        else:
            self.next += 1

x = node(0, 5)
x.incr()
print(x.display)

输出为

(0, 5)
// 没有变化

我尝试做

self.next = self.next + 1
,但没有区别。

重要的是,这个程序仅使用内置的 python 函数,因为我的考试委员会不允许导入函数

python class instance-variables
2个回答
0
投票

由于 self.display 是在 init 方法中定义的,因此您需要在 incr 方法中重新定义它以反映任何更新。

class node:
    def __init__(self, dataStored, nextNode):
        self.data = dataStored
        self.next = int(nextNode)
        self.dataStored = dataStored
        self.display = (dataStored, self.next)

    def incr(self):
        if self.next == -1:
            pass
        else:
            self.next += 1
            self.display = (self.dataStored, self.next)

x = node(0, 5)
x.incr()
print(x.display)

0
投票

x.incr() 正在更新

next
变量,但
display
变量没有更新。

尝试将

print(x.display)
替换为
print(x.next)

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.