Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can't I increment my instance variable?

I want to increment the self.next after initialization. Such that, if var.next = 5 and I did var.incr, then 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)

The output is (0, 5) // no change

I tried doing self.next = self.next + 1, but no difference.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It’s important that this program only uses built-in python functions as my exam board does not allow for imported functions

>Solution :

Since self.display is defined in the init method, you need to redefine it within the incr method to reflect any updates.

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading