为什么我无法增加我的类属性? [重复]

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

我想在初始化后增加 self.next 。这样,如果 var.next = 5 并且我做了 var.incr,那么 var.next = 6

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

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 class pointer-arithmetic
1个回答
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)
© www.soinside.com 2019 - 2024. All rights reserved.