Search code examples
pythonclassmethodsconstructorgetter-setter

Python Setter method in class not giving expected output


I'm trying to update the rank field in the node using setters in Python. Below is the code I've used:

class Tree(object):
    def __init__(self,u):
        self.parent=u
        self.rank=0

    def get_parent(self):
        return self.parent

    def get_rank(self):
        return self.rank

    def set_parent(self,v):
        self.parent=v

    def set_rank(self,v):
        self.rank=v

And then I'm running the following code:

Tree(0).get_rank()
Tree(0).set_rank(5)
Tree(0).get_rank()

Output:

0

Expected Output:

5

Here, the output I'm getting is 0 itself instead of 5 which I'm expecting. Can anybody let me know where exactly am I going wrong in the code or even conceptually?


Solution

  • You have to create an object of your class:

    tree = Tree(0)
    tree.get_rank()
    tree.set_rank(5)
    tree.get_rank()
    
    5